Chart.js: [BUG] Incorrect position of image when using with pointBackgroundColor

Created on 9 Nov 2018  ·  7Comments  ·  Source: chartjs/Chart.js

Expected Behavior

The picture should start rendering from the left top position of the point and should fill up the point.
image

Current Behavior

The picture starts rendering from the centre of the point.
image

Possible Solution

I am not sure about where the problem is, but the following change worked for me.

Add the following line after https://github.com/chartjs/Chart.js/blob/master/src/helpers/helpers.canvas.js#L75

ctx.translate(-1 * radius, -1 * radius);

Steps to Reproduce (for bugs)

Here is a sample codepen that demonstrates the problem: https://codepen.io/anon/pen/aRgjwz

Context

I want to place the user avatars on the graph data points as can see in the expected behavior.

Environment

support

All 7 comments

pointBackgroundColor is a property for specifying background color(s). A CanvasPattern can also be used, but centering is not supported because it's supposed for background patterns. Please use the pointStyle property with a resized Image object for this purpose.

Or, you can simply create a pattern with offset and replace 'no-repeat' with 'repeat'.

  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");

@nagix Thank you for the quick response.

I've tried pattern with offset and with repeat, now the picture seems to be aligned to the center, but it is not visible completely. Please check https://codepen.io/anon/pen/PxzYLj

Just copy and paste my code above. You need to draw the image 4 times to create the pattern.

@nagix It works, thank you very much.

How to create the pattern for text? I just want to place 'AB' inside the circle and align it to center.

Here is the codepen: https://codepen.io/anon/pen/VVPYVr

You may want to use chartjs-plugin-datalabels for text labels. You can also take the same approach as above like this.

tCtx.textAlign = "center";
tCtx.textBaseline = "middle"; 
tCtx.fillText("AB", 0, 0);
tCtx.fillText("AB", size, 0);
tCtx.fillText("AB", 0, size);
tCtx.fillText("AB", size, size);

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

Works great! Thank you for the support.

I think these solutions will help others too. I think I can close the issue now.

Was this page helpful?
0 / 5 - 0 ratings