简体   繁体   中英

draw rectangle on canvas between 2 points

I'm new to javascript and trying to learn how to draw on a canvas. The task is to draw a rectangle between 2 clicked points on a canvas.

 let rectangle = 0; window.addEventListener("load", () => { const canvas = document.getElementById("myCanvas"); const context = canvas.getContext("2d"); let x; let y; canvas.addEventListener("click", (e) => { if (rectangle === 0) { x = e.clientX; y = e.clientY; ++rectangle; } else { xprim = e.clientX; yprim = e.clientY; context.beginPath(); context.fillRect(x, y, xprim - x, yprim - y); context.stroke(); rectangle = 0; } }) })
 .canvas_for_rectangle{ border: 1px solid black; height: 50%; width: 50%; }
 <canvas id="myCanvas" class="canvas_for_rectangle">

Nothing is being shown on the canvas and I have no idea of what is not being done correctly as I am extremely new to the language. What am I doing wrong and what do I have to research?

Do you need to make the canvas bigger? It's default size is only 300x150 if I remember right, so you might simply be drawing outside of that area. The size you give it with CSS isn't relevant for drawing. I would remove your CSS for now and do:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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