当我将canvasPattern用作pointBackgroundColor

时间:2019-02-28 06:55:39

标签: canvas html5-canvas chart.js chartjs-2.6.0 devicepixelratio

预期行为

在所有屏幕分辨率下,图像看起来都应该不错而不会模糊。在PC分辨率下看起来不错。

当前行为

在移动分辨率下,图像看起来很模糊。

这是我的代码

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script>

<canvas id="myChart"></canvas>

JS

var img = new Image();
img.src = "https://techvalor.net/images/avatars/generator/175_1536055288.png";

img.onload = function() {
var canvas = document.getElementById("myChart");

var tempCanvas = document.createElement("canvas");
var tCtx = tempCanvas.getContext("2d");

var size = 40;

tempCanvas.width = size;
tempCanvas.height = size;

tCtx.drawImage(img, 0, 0, img.width, img.height, -size / 2, -size / 2, size, size);         
tCtx.drawImage(img, 0, 0, img.width, img.height, size / 2, -size / 2, size, size); 
tCtx.drawImage(img, 0, 0, img.width, img.height, -size / 2, size / 2, size, size);         
tCtx.drawImage(img, 0, 0, img.width, img.height, size / 2, size / 2, size, size);

var ctx = canvas.getContext("2d");
var fillStyle = ctx.createPattern(tempCanvas, "repeat");

var chart = new Chart(ctx, {
  type: "line",
  data: {
    labels: ["Item 1", "Item 2", "Item 3", "Item 4"],
    datasets: [
      {
        data: [5, 20, 35, 45],
        pointBackgroundColor: fillStyle,
        pointRadius: 20,
        pointBorderColor: "rgb(0,0,0)"
      }
    ]
  },
  options: {
    hover: { mode: null },
    tooltips: { enabled: false }
  }
 });
};

Codepen

https://codepen.io/rajkumar-osm/full/ZPbOOe

我认为这与 devicePixelRatio 有关,但是我不知道在画布上绘制图像时如何考虑它。

0 个答案:

没有答案