简体   繁体   中英

drawing point on canvas not working on safari

I would like to use canvas to draw points on mouseover: my implementation works fine on chrome and firefox, but for some reason it doesn't work on safari (however, drawing a line on mouseover works on safari)

any help would be appreciated!

---> https://draw-9.superhi.com/

code:

let canvas = document.querySelector("canvas");

let x = 0;
let y = 0;


let context = canvas.getContext("2d");
context.strokeStyle = "black";
context.lineWidth = 15;
context.lineCap = "round";

canvas.addEventListener("mousemove", function(e) {
  
    x = e.offsetX;
    y = e.offsetY;

  context.moveTo(x, y);
   context.lineTo(x, y);
    context.stroke();
});

In accordance withthe specs , Safari does

  1. Prune all zero-length line segments from path .
  2. Remove from path any subpaths containing no lines (ie subpaths with just one point).

before tracing it.

Your path is made entirely of such zero-length line segments ( moveTo(x,y); lineTo(x,y) ), and hence nothing is left to be drawn.

Other browsers are buggy here: Firefox bug report , Chrome's .

To do what you want, ie draw a circle, use the arc() method. Also, don't forget to call beginPath() otherwise your path will just grow and you'll end up stroking at the same place over and over leading to bad graphics and performances.

 const canvas = document.querySelector("canvas"); let x = 0; let y = 0; const radius = 7.5; const context = canvas.getContext("2d"); context.strokeStyle = "black"; canvas.addEventListener("mousemove", function(e) { x = e.offsetX; y = e.offsetY; context.beginPath(); context.moveTo(x + radius, y); context.arc(x, y, radius, 0, Math.PI*2); context.fill(); });
 <canvas width="900" height="900">

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