Разбить букву на части
by twobomb three
HTML
<button id="rand">Рандом</button>
JavaScript
document.querySelector("#rand").addEventListener("click",function(){
createWord(String.fromCharCode(1040+getRand(0,33)));
},false);
createWord("У");
function createWord(word){
[...document.body.children].forEach(e=>{
if(e.id != "rand")
document.body.removeChild(e);
});
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
var ctxW = 500;
var ctxH = 300;
canvas.width = ctxW;
canvas.height = ctxH
var text = word;
ctx.font = "200px Impact";
var textHeight = 160;//Высота текста
var textWidth = ctx.measureText(text).width;
var x = 150,y = 200;//Координаты буквы
ctx.fillText(text,x,y);
var imageParts = [];
var countCropY =3;//на сколько частей резать по вертикали
var countCropX =1;//на сколько частей резать по горизонтали
var heightCrop = textHeight/countCropY;
var widthCrop = textWidth/countCropX;
for(var i = 0; i < countCropY;i++){
for(var j = 0; j < countCropX;j++){
imageParts.push(new imagePart(x+widthCrop*j,y-textHeight+heightCrop*i,getRand(0,ctxW-textWidth),getRand(0,ctxH-textHeight),widthCrop,heightCrop,
ctx.getImageData(x+widthCrop*j,y-textHeight+heightCrop*i,widthCrop,heightCrop)))
}
}
function draw(){
ctx.clearRect(0,0,ctxW,ctxH);
ctx.strokeText(text,x,y);
imageParts.forEach(e=>e.draw())
}
draw();
var drag = null,offX = 0,offY = 0;
canvas.addEventListener("mousedown",function(e){
imageParts.forEach(el=>{
if(el.collision({x:e.offsetX,y:e.offsetY})){
drag = el;
offX = el.x- e.offsetX;
offY = el.y - e.offsetY;
return false;
}
});
},false);
document.addEventListener("mouseup",function(e){
if(drag != null){
drag.positionHelper();
draw();
if(imageParts.every(e=>e.x == e.startX && e.y == e.startY)){
ctx.fillText(text,x,y);
alert("Буква собрана!");
}
}
drag = null;
});
...