html5 图片拖动效果,HTML5 P5.js 图片拖动交互效果

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值