简体   繁体   中英

Sharpen the draw in an HTML5 canvas

Today I started learning how to work with canvas by doing a basic loading circle animation. Everything works perfect in small res (ca. 100×100 px) but when I tried much larger it all went distorted and blurred and it looks really bad. So this is my question: Can I somehow turn on some anti-aliasing on or somehow make it more sharpen? I already found plenty of sharpening algorithms but for images and I'm not sure if it will work with this.

Circle loading example: (code is not perfect or even finished because I'm still stuck on that blur)

JSFiddle

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var int_count = 0;
var circ_angle = 1.5;
var count = 10;

var interval = setInterval(function() {

  if (int_count == count) {
    clearInterval(interval);
  }
  ctx.clearRect(0, 0, 1000, 1000);

  ctx.beginPath();

  ctx.arc(100, 70, 50, 1.5 * Math.PI, -1 * Math.PI, true);
  ctx.lineWidth = 1;
  ctx.strokeStyle = "#717171";
  ctx.stroke();

  ctx.beginPath();

  //1.5 = 0%; 1 = 1/4; 0.5 = 2/4; 0 = 3/4 -1 = full
  ctx.font = "40px sarpanch";
  ctx.arc(100, 70, 50, 1.5 * Math.PI, circ_angle * Math.PI, true);
  //color
  if (int_count >= 5 && int_count < 10) {
    ctx.strokeStyle = "#ff8000";
  }
  else if (int_count >= 9) {
    ctx.strokeStyle = "#F00";
  }
  else {
    ctx.strokeStyle = "#3a9fbe";
  }

  ctx.fillText("" + int_count + "", 88, 83);

  ctx.lineWidth = 3;
  ctx.stroke();

  int_count += 1;
  circ_angle += (-0.2);
}, 500);

Add the following attributes :

width="759" height="394"

to your <canvas> instead of specifying them in your css

Never resize your canvas with CSS. Instead, set the canvas size with the width and height attributes:

<canvas id="canvas" width="759" height="394"></canvas>

Remove the CSS rules for the canvas.

Next, you'll have to scale every part with JavaScript:

Working demo

// …
ctx.arc(150, 150, 100, 1.5*Math.PI,-1*Math.PI,true); // instead of 100, 70, 50

// …
ctx.font = "60px sarpanch"; // instead of 40px
ctx.arc(150, 150, 100, 1.5*Math.PI,circ_angle*Math.PI,true); // instead of 100, 70, 50

// …
ctx.fillText(int_count, 130, 170); // instead of 88, 83
// …

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