JavaScriptcanvas基于数组生成柱状图代码实例
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
JavaScriptcanvas基于数组⽣成柱状图代码实例HTML5 的 canvas 元素使⽤ JavaScript 在⽹页上绘制图像。
画布是⼀个矩形区域,您可以控制其每⼀像素。
canvas 拥有多种绘制路径、矩形、圆形、字符以及添加图像的⽅法。
canvas 元素本⾝是没有绘图能⼒的。
所有的绘制⼯作必须在 JavaScript 内部完成:
canvas柱状图
var arr = [
{ id: 1001, price: 100 },
{ id: 1002, price: 150 },
{ id: 1003, price: 200 },
{ id: 1004, price: 70 },
{ id: 1005, price: 300 }
];
var gap = 20;
var canvas = document.querySelector("canvas");
var ctx;
init();
function init() {
canvas.width = 400;
canvas.height = 300;
ctx = canvas.getContext("2d");
var max = arr.reduce((value, item) => {
return value < item.price ? item.price : value;
}, arr[0].price);
//max⾼为300的4/5,其他的⾼为:300*(4/5)/(max) * h maxh:240 = othersh: ? ? = 240
var scaleHeight = 300 * 4 / 5 / max;
//每个柱状图的宽为总宽-间隙宽除个数
var width = (400 - (gap * (arr.length + 1))) / arr.length;
createChart(width, scaleHeight);
}
function createChart(w, hs) {
ctx.fillStyle = "rgba(0,0,0,0.7)";
ctx.fillRect(0, 0, 400, 300);
var x = 0;
for (var i = 0; i < arr.length; i++) {
x += gap;
ctx.fillStyle = "orange";
var h = hs * arr[i].price;
ctx.fillRect(x, 300 - h, w, h);
x += w;
}
}
效果:
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。