简体   繁体   中英

Create dynamic diagonal gradient using javascript for html5 canvas?

Is there a way to create a diagonal gradient doing something like this? My attempts only give me a vertical or horizontal

 _canvas = document.getElementById('canvas');
 _stage = _canvas.getContext('2d');

 var gradient = _stage.createLinearGradient(0, 0, buttonEndX, buttonEndY);
 gradient.addColorStop(0, "white");
 gradient.addColorStop(1, "blue");

Your code should work fine. Do you call context.fillRect() after previously setting context.fillStyle = gradient and are your buttonEndX and buttonEndY variables set to meaningful values?

 var buttonEndX = 100, buttonEndY = 100; _canvas = document.getElementById('canvas'); _stage = _canvas.getContext('2d'); var gradient = _stage.createLinearGradient(0, 0, buttonEndX, buttonEndY); gradient.addColorStop(0, "white"); gradient.addColorStop(1, "blue"); _stage.fillStyle = gradient; _stage.fillRect(10, 10, 200, 100); 
 <canvas id="canvas" width="100" height="100"></canvas> 

The above code renders as (Chrome 48):

在此处输入图片说明

You seem to have it correct, Patrick. This codepen shows an example of how the code you have should potentially render. Which brings up the question of what are your buttonEndX and buttonEndY values? Maybe try something as simple as a console.log(bottonEndX) to make sure that those values are what you expect them to be.

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