I am trying to make a canvas you can draw on in vanilla JavaScript. I managed to make it so you can draw on it. However, I want to make it so you can see the dot that will be drawn if you press down. I basically want a circle that has the same styling as the drawn lines to follow the cursor. This circle is only supposed to show when it is on the canvas.
I tried a lot of solutions I found on the web, but none of them worked for me. I also set the cursor to none so a custom one could be drawn in JavaScript.
Here are the necessary parts of the HTML and JavaScript code:
var imageLoader = document.getElementById('imageLoader'); imageLoader.addEventListener('change', handleImage, false); var canvas = document.getElementById('imageCanvas'); var ctx = canvas.getContext('2d'); var img; function handleImage(e){ var reader = new FileReader(); reader.onload = function(event){ img = new Image(); img.onload = function(){ var ratio = this.height / this.width; canvas.height = canvas.width * ratio; ctx.drawImage(img,0,0,canvas.width, canvas.height); } img.src = event.target.result; } reader.readAsDataURL(e.target.files[0]); } var pos = { x: 0, y: 0 }; document.addEventListener('mousemove', draw); document.addEventListener('mousedown', setPosition); document.addEventListener('mouseenter', setPosition); function setPosition(e) { var rect = canvas.getBoundingClientRect(); pos.x = e.clientX - rect.left pos.y = e.clientY - rect.top } function draw(e) { canvas.style.cursor = "none"; if (e.buttons !== 1) return; console.log(pos.x) ctx.beginPath(); ctx.lineWidth = 5; ctx.lineCap = 'round'; ctx.strokeStyle = '#c0392b'; ctx.moveTo(pos.x, pos.y); setPosition(e); ctx.lineTo(pos.x, pos.y); ctx.stroke(); canvas.style.cursor = "default"; }
<input type="file" id="imageLoader"/> <div class="container" id="container"> <canvas id="imageCanvas"></canvas> </div>
没有评论:
发表评论