glassraven
glassraven

Reputation: 323

Canvas/JS: can't change the lineWith without altering previous line

I'm trying to change the lineWith of a free-hand drawing in canvas (like paint) with a simple click function. But as I click in this div, the previous drawing gets also the new lineWidth and doesn't perserve it's original state. Ho can I solve this issue?

JavaScript

var el = document.getElementById('canvas');
var ctx = el.getContext('2d');
var isDrawing;
var redStroke= ctx.strokeStyle = "#FF0000";

el.onmousedown = function(e) {
  isDrawing = true;
  ctx.moveTo(e.offsetX, e.offsetY);
    //ctx.lineWidth=1;->default
};

el.onmousemove = function(e) {
  if (isDrawing) {
    ctx.lineTo(e.offsetX, e.offsetY);
      ctx.stroke();
  }


};
el.onmouseup = function() {
  isDrawing = false;
};

$('#medium').click(function(){
    var mediumStroke=ctx.lineWidth=5;
   mediumStroke; 
});

$('#large').click(function(){
    var largeStroke=ctx.lineWidth=20;
   largeStroke; 
});

HTML:

<div class="container">
            <canvas id="canvas" width="800" height="500"></canvas>

            <div class= "stroke">
                <p id="medium">Medium Stroke</p>
                <p id="large">Thick Stroke</p>
            </div>

        </div>

Upvotes: 1

Views: 83

Answers (1)

ɢʀᴜɴᴛ
ɢʀᴜɴᴛ

Reputation: 32879

You'll need to use beginPath() method before drawing a line ...

var el = document.getElementById('canvas');
var ctx = el.getContext('2d');
var isDrawing;
var redStroke = ctx.strokeStyle = "#FF0000";

el.onmousedown = function(e) {
    isDrawing = true;
    
    ctx.beginPath(); //<-- use this
    
    ctx.moveTo(e.offsetX, e.offsetY);
};

el.onmousemove = function(e) {
    if (isDrawing) {
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
    }
};

el.onmouseup = function() {
    isDrawing = false;
};

$('#medium').click(function() {
    var mediumStroke = ctx.lineWidth = 5;
});

$('#large').click(function() {
    var largeStroke = ctx.lineWidth = 20;
});
canvas {
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container"> <canvas id="canvas" width="800" height="500"></canvas>
    <div class="stroke">
        <p id="medium">Medium Stroke</p>
        <p id="large">Thick Stroke</p>
    </div>
</div>

Upvotes: 1

Related Questions