demo(pc/移动兼容) 觉得好看的话
github 各位大爷点个赞👍
前言
为什么要做,公司要做
技术栈
react mobx threejs h5-canvas
图片展示
核心代码逻辑
数组存储一系列图片文字数据,canvas依次将他们渲染出来。
arr = [{
angle:-4.9991865390311006
element:img
height:366.64477704140256
scale:1
type:"image"
width:366.6447770414025
x:0
y:0
}, {
angle:-4.9991865390311006
element:img
height:366.64477704140256
scale:1
type:"image"
width:366.6447770414025
x:0
y:0
}]
为了便于计算,运用到canvas坐标系的平移与旋转,因为相对坐标容易计算,灵活运用ctx.save(),以及ctx.restore(); 清空以及保存坐标系,每个图片文字元素都有自己的独特的坐标系。
ctx.save();
ctx.translate(
canvas_props.width*block_props.x + x,
canvas_props.height*block_props.y + y
);
ctx.scale(scale, scale);
ctx.rotate(rad);
switch (type) {
case "image":
ctx.drawImage(
element,
-width/2 ,
-height/2 ,
width,
height
);
break;
case "text":
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `${font.weight} ${font.size} ${font.family}`;
ctx.fillStyle = font.color;
ctx.fillText(
content,
0,0
);
break;
default:
break;
}
ctx.restore();
3d效果,自然是运用three.js这种优秀框架来做啦。首先建模,建立类似酒瓶模型,大概就是几个圆柱+圆球+瓶盖圆柱,将之前绘制的2d canvas转化成图片,记得处理好跨域问题,canvas不支持跨域,crossOrigin="anonymous",在dom元素上面加上这个就好了。直接给之前的圆柱模型表面材质使用之前绘制的canvas生成的图片就好了。
遇到的困难
- 我的审美啊,真心不行。
- 代码太多,逻辑混乱,写不下去了。
- ispointinpath,这个mmp的canvas内置API真心蛋疼,必须在绘制完成后才能去识别。而我自己手动去做是否点击到某个图形又很困难,但最终解决办法还是我手动去检测是否点到某个元素。