本文共 1703 字,大约阅读时间需要 5 分钟。
JavaScript
语言:
JaveScriptBabelCoffeeScript
确定
"use strict";
/*
Johan Karlsson (DonKarlssonSan)
Dragging images
*/
var Rectangle = (function() {
function Rectangle(pos, img) {
this.pos = pos;
this.img = img;
this.width = img.width;
this.height = img.height;
}
Rectangle.prototype.draw = function() {
image(this.img, this.pos.x, this.pos.y);
};
Rectangle.prototype.hits = function(hitpos) {
if (hitpos.x > this.pos.x &&
hitpos.x < this.pos.x + this.width &&
hitpos.y > this.pos.y &&
hitpos.y < this.pos.y + this.height) {
return true;
}
return false;
};
return Rectangle;
}());
var rects;
var dragRec;
var isDragging;
var clickOffset;
var imgCb;
function preload() {
imgCb = loadImage("/assets/coolgirl.jpg");
}
function setup() {
rects = [];
placeImages();
isDragging = false;
createCanvas(windowWidth, windowHeight);
}
function placeImages() {
var numImage = 5;
for (var i = 0; i < numImage; i++) {
var pos = randomPos();
rects.push(new Rectangle(pos, imgCb));
}
}
function randomPos() {
return createVector(random(0, windowWidth), random(0, windowHeight));
}
function draw() {
clear();
rects.forEach(function(r) {
return r.draw();
});
}
function mousePressed() {
var m = createVector(mouseX, mouseY);
var index;
rects.forEach(function(r, i) {
if (r.hits(m)) {
clickOffset = p5.Vector.sub(r.pos, m);
isDragging = true;
dragRec = r;
index = i;
}
});
if (isDragging) {
putOnTop(index);
}
}
function putOnTop(index) {
rects.splice(index, 1);
rects.push(dragRec);
}
function mouseDragged() {
if (isDragging) {
var m = createVector(mouseX, mouseY);
dragRec.pos.set(m).add(clickOffset);
}
}
function mouseReleased() {
isDragging = false;
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
转载地址:http://mincl.baihongyu.com/