防止所有画布线改变颜色

时间:2018-09-22 20:30:32

标签: javascript

当我单击按钮更改线条颜色时,将要绘制线条。它会更改我之前绘制的所有线条。如何使旧线条保持其原始颜色? 解释起来很简单,因为我是js新手,谢谢!

var can = document.getElementById("canvas");
var bRed = document.getElementById("bRed");
var bGreen = document.getElementById("bGreen");
var bBlue = document.getElementById("bBlue");
var bBlack = document.getElementById("bBlack");
var pen  = document.getElementById("canvas").getContext("2d");
var mouseClicked = false, mouseReleased = true;

//Events
can.addEventListener("click", onMouseClick, false);
can.addEventListener("mousemove", onMouseMove, false);

//Buttons
bRed.onclick= function (){
    pen.strokeStyle = "red";
}

bGreen.onclick = function (){
    pen.strokeStyle = "green";
}

bBlue.onclick = function (){
    pen.strokeStyle = "blue";
}

bBlack.onclick = function (){
    pen.strokeStyle = "black";
}

//Functions

//Draw
function onMouseMove(evt){
    if(mouseClicked){
    pen.lineTo(evt.clientX, evt.clientY);
    pen.lineWidth = 5;
    pen.stroke();
    }
}

//Stop/start
function onMouseClick(evt){
    mouseClicked = !mouseClicked;
    pen.moveTo(evt.clientX, evt.clientY);
}
            <canvas id="canvas" width="200" height="200"></canvas>
            <br>
            <button id="bRed" type="button"> Red </button>
            <br>
            <button id="bGreen" type="button" > Green </button>
            <br>
            <button id="bBlue" type="button"> Blue </button>
            <br>
            <button id="bBlack" type="button"> Black </button>

0 个答案:

没有答案