简体   繁体   English

HTML5画布-着色问题

[英]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 HTML部分是

    <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">
              <option 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. 例如,无需一直保持调用getContext(),只需调用一次即可。 Same goes for getElementById() no need to call it more than once. getElementById()也一样,无需多次调用。 I also moved your events out of the canvas tag and into the javascript. 我还将您的事件从canvas标签移到了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()". 您对stroke()和closePath()的调用顺序似乎有点奇怪……我已解决了这个问题,但事实并非如此……最后,您唯一的问题是您编写了“ beginpath()” ”,而不是“ beginPath()”。

Have a look at the fixed version on jsFiddle . 看看jsFiddle固定版本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM