开发者

HTML5 Canvas - Coloring Problem

I am using the Following Code. It works fine but the problem is that when i Change the colour of my pencil, then the things that i have already drawn on the canvas its colour also changes. I cant figure it out why is it happening and how to fix it , Any Idea's ?

 <script type="text/javascript"> 

function cnvs_getCoordinates(e) {

    x = e.clientX + document.body.scrollLeft;
    y = e.clientY + document.body.scrollTop;
    var c = document.getElementById("coordiv");
    var context = c.getContext("2d");
    context.lineWidth = 5;
    context.strokeStyle = document.getElementById("dcol").value;

    if (started == 1) {
        context.lineTo(x, y);
        context.stroke();
    }
    else {
        context.moveTo(x, y);
    }
}

function a() {
    started = 1;
    context.beginpath();
}

function b() {
    started = 0;
    context.closePath();
}

</script>

The HTML part is

    <body>
<div style="border: thin solid black">hi
  <canvas id="coordiv"   onmousemove="cnvs_getCoordinates(event)" onmousedown="a()" onmouseup="b()" > </canvas>

   <select  id="dcol" name="Colour">
              <opti开发者_开发问答on value="black" selected="selected">Black</option>
              <option value="red">Red</option>
              <option value="green"> Green</option>
              <option value="blue">Blue</option>
              <option value="white">** ERASER **</option>
            </select>
</div>
</body>


There were a few odd things about your code that I took the liberty of fixing. For instance, no need to keep calling getContext() all the time, just call it once. Same goes for getElementById() no need to call it more than once. I also moved your events out of the canvas tag and into the javascript. I was really puzzled by your problem when I first experienced it. The order of your calls to stroke() and closePath() seemed a little wonky... I fixed that, but that turned out not to be the problem... in the end your only problem was that you wrote "beginpath()" instead of "beginPath()".

Have a look at the fixed version on jsFiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜