Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

HTML Canvas Eraser and Pen not working as intended

I have a canvas that has a pen and eraser button. Unfortunately, clicking either of the buttons does nothing. I want the eraser to change into the color white and the pen to be black. I cannot figure out what is causing my code to not work. Here is my javascript code.

var mousePressed = false;
var lastX, lastY;
var ctx = document.getElementById('myCanvas').getContext("2d");

function InitThis() {
    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush();
        }
    });

    $('#myCanvas').mouseleave(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush();
        }
    });
    
    $("#pen").click(function() {
        ctx.strokeStyle = "#000000";
    });

    $("#erase").click(function() {
        ctx.strokeStyle = "#FFFFFF";
    });
    
    var canvas = document.getElementById('myCanvas');
    var canvasOffsetX = canvas.offsetLeft;
    var canvasOffsetY = canvas.offsetTop;

    canvas.width = window.innerWidth - canvasOffsetX;
    canvas.height = window.innerHeight - canvasOffsetY;
    
    drawImage();
}

function drawImage() {
    var image = new Image();
    image.src = 'transparent.jpg';
    $(image).load(function () {
        ctx.drawImage(image, 0, 0);
        cPush();
    });    
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x;
    lastY = y;
}

var cPushArray = new Array();
var cStep = -1;

function cPush() {
    cStep++;
    if (cStep < cPushArray.length) { cPushArray.length = cStep; }
    cPushArray.push(document.getElementById('myCanvas').toDataURL());
}

function cUndo() {
    if (cStep > 0) {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}

function cRedo() {
    if (cStep < cPushArray.length-1) {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}

// Set up touch events for mobile, etc
const canvas = document.getElementById('myCanvas');
canvas.addEventListener("touchstart", function (e) {
        mousePos = getTouchPos(canvas, e);
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousedown", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchend", function (e) {
  var mouseEvent = new MouseEvent("mouseup", {});
  canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchmove", function (e) {
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousemove", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);

// Get the position of a touch relative to the canvas
function getTouchPos(canvasDom, touchEvent) {
  var rect = canvasDom.getBoundingClientRect();
  return {
    x: touchEvent.touches[0].clientX - rect.left,
    y: touchEvent.touches[0].clientY - rect.top
  };
}

// Prevent scrolling when touching the canvas
document.body.addEventListener("touchstart", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchend", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchmove", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);

function save(){
    var canvas = document.querySelector("#myCanvas");
    var image = canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");

    var element = document.createElement('a');
    var filename = 'drawing.jpg';
    element.setAttribute('href', image);
    element.setAttribute('download', filename);
    element.click();
}

var hea der = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");
  this.className += " active";
  });
}

Here is a codepen with the entire code. As you can see, the pen and eraser buttons do nothing. https://codepen.io/adilene/pen/zYJQYXq

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I am not a canvas guy, but looking into the code, found that
ctx.strokeStyle = $('#selColor').val(); this is causing issue. Commenting this line worked for me.

var mousePressed = false;
var lastX, lastY;
var ctx = document.getElementById('myCanvas').getContext("2d");
var stroke = "#000000";

function InitThis() {
    $('#myCanvas').mousedown(function (e) {
        mousePressed = true;
        Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, false);
    });

    $('#myCanvas').mousemove(function (e) {
        if (mousePressed) {
            Draw(e.pageX - $(this).offset().left, e.pageY - $(this).offset().top, true);
        }
    });

    $('#myCanvas').mouseup(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush();
        }
    });

    $('#myCanvas').mouseleave(function (e) {
        if (mousePressed) {
            mousePressed = false;
            cPush();
        }
    });
    
    $("#pen").click(function() {
        ctx.strokeStyle = stroke;
    });

    $("#erase").click(function() {
        stroke = ctx.strokeStyle;
        ctx.strokeStyle = "#FFFFFF";
    });
    
    var canvas = document.getElementById('myCanvas');
    var canvasOffsetX = canvas.offsetLeft;
    var canvasOffsetY = canvas.offsetTop;

    canvas.width = window.innerWidth - canvasOffsetX;
    canvas.height = window.innerHeight - canvasOffsetY;
    
    drawImage();
}

function drawImage() {
    var image = new Image();
    image.src = 'transparent.jpg';
    $(image).load(function () {
        ctx.drawImage(image, 0, 0);
        cPush();
    });    
}

function Draw(x, y, isDown) {
    if (isDown) {
        ctx.beginPath();
        // Changing this line worked
        //ctx.strokeStyle = $('#selColor').val();
        ctx.lineWidth = $('#selWidth').val();
        ctx.lineJoin = "round";
        ctx.moveTo(lastX, lastY);
        ctx.lineTo(x, y);
        ctx.closePath();
        ctx.stroke();
    }
    lastX = x;
    lastY = y;
}

var cPushArray = new Array();
var cStep = -1;

function cPush() {
    cStep++;
    if (cStep < cPushArray.length) { cPushArray.length = cStep; }
    cPushArray.push(document.getElementById('myCanvas').toDataURL());
}

function cUndo() {
    if (cStep > 0) {
        cStep--;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}

function cRedo() {
    if (cStep < cPushArray.length-1) {
        cStep++;
        var canvasPic = new Image();
        canvasPic.src = cPushArray[cStep];
        canvasPic.onload = function () { ctx.drawImage(canvasPic, 0, 0); }
    }
}

// Set up touch events for mobile, etc
const canvas = document.getElementById('myCanvas');
canvas.addEventListener("touchstart", function (e) {
        mousePos = getTouchPos(canvas, e);
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousedown", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchend", function (e) {
  var mouseEvent = new MouseEvent("mouseup", {});
  canvas.dispatchEvent(mouseEvent);
}, false);
canvas.addEventListener("touchmove", function (e) {
  var touch = e.touches[0];
  var mouseEvent = new MouseEvent("mousemove", {
    clientX: touch.clientX,
    clientY: touch.clientY
  });
  canvas.dispatchEvent(mouseEvent);
}, false);

// Get the position of a touch relative to the canvas
function getTouchPos(canvasDom, touchEvent) {
  var rect = canvasDom.getBoundingClientRect();
  return {
    x: touchEvent.touches[0].clientX - rect.left,
    y: touchEvent.touches[0].clientY - rect.top
  };
}

// Prevent scrolling when touching the canvas
document.body.addEventListener("touchstart", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchend", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);
document.body.addEventListener("touchmove", function (e) {
  if (e.target == canvas) {
    e.preventDefault();
  }
}, false);

function save(){
    var canvas = document.querySelector("#myCanvas");
    var image = canvas.toDataURL("image/jpg").replace("image/jpg", "image/octet-stream");

    var element = document.createElement('a');
    var filename = 'drawing.jpg';
    element.setAttribute('href', image);
    element.setAttribute('download', filename);
    element.click();
}

var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");
  this.className += " active";
  });
}
:root {
    --b: white; /* container bgs */
    --bw: 3px; /* border width */
    --bc: #34f2ff; /* border color */
    --bcc: #34f2ff; /* border color outset */
    --h: #dbfcff; /* header bgs */
    --pink: #e74492;
    --bt: solid;
    --color:#000;
}

* {
    box-sizing: border-box;
    scrollbar-color:#e74492 #fff;
    scrollbar-width:thin;
    cursor:url('https://files.catbox.moe/h0vf27.png'), pointer;
}

::-webkit-scrollbar{
    width: 10px;
    height: 10px;
}

::-webkit-scrollbar-thumb{
    background: #e74492;
    border: 3.5px var(--bt) #FFFFFF;
    border-radius: 0px;
}

::-webkit-scrollbar-thumb:hover{
    background: #ed75ae;
}

::-webkit-scrollbar-track{
    background: #FFFFFF;
    border-radius: 0px;
    box-shadow: inset 0px 0px 0px 0px #F0F0F0;
}

::selection {
    background: #34f2ff;
    color:white;
}
 
::-moz-selection {
    background: #34f2ff;
    color:white;
}

a{
    text-decoration: none;
    color:#e74492;
    text-shadow: 2px 2px 1px #34f2ff;
    transition:0.3s;
}

a:hover{
    
    transition:0.3s;
    letter-spacing:1.5px;
}

@font-face{
    font-family:'Pixel Operator';
    src:url(https://files.catbox.moe/kyguk9.ttf);
}

@font-face{
    font-family:'Orbitron';
    src:url(https://files.catbox.moe/cckohn.ttf);
}

body{
    background-color:var(--bg);
    text-align:center;
    margin:0px;
    padding:0;
    overflow:hidden;
    font-family: 'Pixel Operator';
    font-size:20px;
    animation:fadeEffect 0.5s;
    height:100%;
}

@keyframes fadeEffect {
    from {opacity: 0;}
    to {opacity: 1;}
}

p{
    line-height:100%;
}

a{
    text-decoration: none;
    color:#e74492;
    text-shadow: 2px 2px 1px #34f2ff;
    transition:0.3s;
}

a:hover{
    letter-spacing: 2px;
}

header{
    color:#e74492;
    font-family: 'Orbitron';
    font-size:20px;
}

ul{
    list-style:none;
}

ul li:before{
    content:"\25A0 ";
    color:#e74492;
    display:inline-block;
    width:1em;
    margin-left:-1.3em;
}

img {
    user-drag: none;
    -webkit-user-drag: none;
    user-select: none;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}

button{
    border: var(--bw) var(--bt) var(--bc);
    outline: none;
    padding: 5px 8px;
    background-color: #dbfcff;
    font-family: 'Pixel Operator';
    font-size:16px;
    margin:2px 0px;
    transition:0.2s;
    color:#e74492;
}

button:hover, .active{
    background-color: #e74492;
    color:white;
    transition:0.2s;
}

.btn:hover, .active{
    background-color: #e74492;
    color:white;
    transition:0.2s;
}

#container {
    height: 100vh;
    display: flex;
}

#drawing-board{
    background-color:white;
}

#toolbar {
    display:flex;
    flex-direction: column;
    padding: 10px;
    width: 120px;
    text-align:center;
    background-color: var(--h);
    border:var(--bw) var(--bt) var(--bc);
}

#toolbar * {
    margin-bottom:10px;
}

#toolbar input {
    width: 100%;
    border:var(--bw) var(--bt) var(--bc);
}

#toolbar input{
    border:var(--bw) var(--bt) var(--bc);
    background-color:white;
}

canvas {
    touch-action: none;
}

.thumbnail img{
    width:100%;
    height: 200px;
    object-fit: cover;
    box-sizing: border-box;
    padding:10px;
    background-color:#dbfcff;
    border: var(--bw) var(--bt) var(--bc);
    display:block;
}

.thumbnail img:hover{
    opacity:0.8;
    transition:0.3s;
}

.wrap{
    width:100%;
    margin:auto;
    gap:10px;
    display: flex;
    flex-wrap:wrap;
    justify-content: center;
}

.wrap div{
    width:calc(24.8% - 5px);
}

.wrap div div{
    width:100%;
}

input::file-selector-button {
    border: var(--bw) var(--bt) var(--bc);
    outline: none;
    padding: 5px 8px;
    background-color: #dbfcff;
    font-family: 'Pixel Operator';
    font-size:16px;
    margin:2px 10px;
    transition:0.2s;
    color:#e74492;
}

 input::file-selector-button:hover {
    background-color: #e74492;
    color:white;
    transition:0.2s;
    cursor:url('https://files.catbox.moe/h0vf27.png'), pointer;
}

#name input, #url input{
    border:var(--bw) var(--bt) var(--bc);
    background-color:white;
}

#myFile{
    font-family:'Pixel Operator';
    font-size:20px;
}

.desc{
    padding:5px 10px;
    border-left:var(--bw) var(--bt) var(--bc);
    border-bottom:var(--bw) var(--bt) var(--bc);
    border-right:var(--bw) var(--bt) var(--bc);
    box-sizing:border-box;
    background-color:white;
        }
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <style>
        button{
            width:100%;
        }
    </style>
    <body onload="InitThis();">
        <section id="container">
            <div id="toolbar">
                <header>OEKAKI</header>
                <label for="selColor">Pen Color</label>
                <input id="selColor" name="selColor" type="color">
                <label for="selWidth">Line Width</label>
                <input id="selWidth" name="selWidth" type="number" value="3">
                <div style="margin-bottom:0px;" id="myDIV">
                    <button id="pen" class="btn active">Pen</button>
                    <button id="erase" class="btn">Eraser</button>
                </div>
                <button onclick="javascript:cUndo();return false;">Undo</button>
                <button onclick="javascript:cRedo();return false;">Redo</button>
                <button class="download" onclick="save()">Save</button>
                <div>Feel free to upload your images to the gallery for a chance to be featured!</div>
                <a href="/gallery.html"><button style="margin-bottom:0px;">Gallery</button></a>
                <button onclick="javascript:drawImage();return false;">Clear</button>
            </div>
            <div class="drawing-board">
                <canvas id="myCanvas"></canvas>
            </div>
        </section>
        
        <script src="script.js"></script>
    </body>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading