When user upload image and when he try to drag the image , the image will display shadow along with dragging, but i don't want to display the shadow....
codepen : https://codepen.io/kidsdial/pen/xMNbVz
$(document).ready(function () {
// dont have a webserver so im using base64string instead
var maskedImageUrlb ="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaAAAAGECAYAAABwC/R5AAAACXBIWXMAAC4jAAAuIwF4pT92AAAF+mlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDIgNzkuMTYwOTI0LCAyMDE3LzA3LzEzLTAxOjA2OjM5ICAgICAgICAiPiA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPiA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdEV2dD0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlRXZlbnQjIiB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iIHhtbG5zOnBob3Rvc2hvcD0iaHR0cDovL25zLmFkb2JlLmNvbS9waG90b3Nob3AvMS4wLyIgeG1wOkNyZWF0b3JUb29sPSJBZG9iZSBQaG90b3Nob3AgQ0MgMjAxOCAoV2luZG93cykiIHhtcDpDcmVhdGVEYXRlPSIyMDE5LTAxLTE5VDE4OjExOjMxKzA1OjMwIiB4bXA6TWV0YWRhdGFEYXRlPSIyMDE5LTAxLTE5V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I9CpwHXI43kUq15QhIVRmm/A08twPvB54GXIblI9WaIyBVaV/gVxR/7XGYOBTuQmBHwY8tqSSOgFSl9cCHC3y8UWLLnKcC52P5SI3iCEgZrgFevcDHuIwos40LjyMpgyMgZTiV2GW6H1cDzyTO5rF8pAazgJRhDHgnUUQP9/g1twKHjn/NunJiSaqSU3DKtgg4GXgNcDSxZc8iYmHBQ0TxfIu4mVRSi/x/pI20G7Wjx7YAAAAASUVORK5CYII=";
// maskedImage two
var mask2 = $(".container").mask({
maskImageUrl: maskedImageUrlb,
onMaskImageCreate: function (img) {
// add your style to the img example below
img.css({ "position" : "fixed" , "left": 173, "top": 1 })
}
});
fileupa2.onchange = function () {
mask2.loadImage(URL.createObjectURL(fileupa2.files[0]));
};
}); // end of document ready
// jq plugin for mask
(function ($) {
var JQmasks = [];
$.fn.mask = function (options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function (div) { },
}, options);
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event){
return { x: event.pageX || event.offsetX, y: event.pageY || event.offsetY };
}
container.selected = function (ev) {
var pos = container.mousePosition(ev);
var item =$(".masked-img canvas").filter(function(){
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] >0
});
JQmasks.forEach(function(el){
var id = item.length> 0 ? $(item).attr("id") : "";
if (el.id ==id )
el.item.enable();
else el.item.disable();
});
};
container.enable = function(){
draggable = true;
$(canvas).attr("active", "true");
div.css({ "z-index": 2 });
}
container.disable = function(){
draggable = false;
$(canvas).attr("active", "false");
div.css({ "z-index": 1 });
}
container.onDragStart = function (evt) {
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
};
container.getImagePosition = function () {
return { x: settings.x, y: settings.y, scale: settings.scale };
};
container.onDragOver = function (evt) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
container.updateStyle();
}
};
container.updateStyle = function () {
clearTimeout(timeout);
timeout = setTimeout(function () {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.globalCompositeOperation = "source-over";
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function () {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({ "width": image.width, "height": image.height });
};
img = new Image();
img.src = settings.imageUrl;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
settings.x =settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale )) / 2 : settings.x;
settings.y =settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale )) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}, 0);
};
// change the draggable image
container.loadImage = function (imageUrl) {
if (img)
img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle();
};
// change the masked Image
container.loadMaskImage = function (imageUrl, from) {
if (div)
div.remove();
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
div.find("canvas").on('touchstart mousedown', function (event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function (event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({item: container , id: settings.id})
return container;
};
}(jQuery));
.container {
border: 1px solid #DDDDDD;
display: flex;
background: red;
width:612px;
height:612px;
}
.container canvas {
display: block;
}
.masked-img {
overflow: hidden;
margin-top: 50px;
position: relative;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
image 2
<input id="fileupa2" type="file" >
<div class="container">
</div>
I don't want to display shadow when dragging....
Please let me know if you have any doubts on this....
Thanks in Advance....
Listen for the dragStart event :
div.find("canvas").on('dragstart', function (event) {
so you can use DataTransfer.setDragImage() :
When a drag occurs, a translucent image is generated from the drag target (the element the dragstart event is fired at), and follows the mouse pointer during the drag. This image is created automatically, so you do not need to create it yourself. However, if a custom image is desired, the DataTransfer.setDragImage() method can be used to set the custom image to be used. The image will typically be an element but it can also be a or any other image element.
And update the container.onDragStart function to :
container.onDragStart = function (evt) {
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
evt.originalEvent.dataTransfer.setDragImage(null, 0, 0); // add this line
};
Here's an example with a custom " shadow" iamge :
$(document).ready(function() {
// dont have a webserver so im using base64string instead
var maskedImageUrlb = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaAAAAGECAYAAABwC/R5AAAACXBIWXMAAC4jAAAuIwF4pT92AAAF+mlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPD94cGFja2V0IGJlZ2luPSLvu78iIGlkPSJXNU0wTXBDZWhpSHpyZVN6TlRjemtjOWQiPz4gPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iQWRvYmUgWE1QIENvcmUgNS42LWMxNDIgNzkuMTYwOTI0LCAyMDE3LzA3LzEzLTAxOjA2OjM5ICAgICAgICAiPiA8cmRm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mwa4B3A6uwgUpV8BaoM2/F7D2AIeA/wHCwfdZC/BJTBkTdcDjydmHbzepg6yV8EyrCE+KXbxRdA64jptjuzg0jZXISgLF1bhDAMfIjYtXo0N4pUD46AlOGH2QEq9gPgLGBTdhCpTiwgZVhGN0Y/G4F3AjdnB5HqqAu/BFQ/K7IDlGwUOB94BpaPNCOvASnD/wUGs0OU5CbirJ4N2UGkunMKTlVbSjvLZzNxT8+1yTmkxnAKTlXbOztAwcaIHav/I5aPNC+OgFS1ldkBCnQHMep5MDuI1ESOgFS1A7MDFGAr8EbghVg+Ut8sIFVtJc3eeuaLxBY6V2YHkZrOVXCq2h+APbND9OE+Ygud+5NzSK3hCEhV2pvmlc8mYrrtcCwfqVAuQlCVXpQdYB62Ah8ELsW926RSWECq0ouzA/RgCLiA2DR0ODeK1G5eA1KVfg88JTvEDEaAzwKfxCOxpUo4AlJV9qOe5TNGHAp3AbGbgaSKWECqymHZAabxbeKMnoeTc0idZAGpKnUa/dwAnIs3kUqpLCBVZUl2AOIY7HOAe7KDSLKAVJ0tic+9higez+aRasQbUVWVjOmuDcCpwLOxfKTacRm2qrIYeGz8z7I9CpwHXI43kUq15QhIVRmm/A08twPvB54GXIblI9WaIyBVaV/gVxR/7XGYOBTuQmBHwY8tqSSOgFSl9cCHC3y8UWLLnKcC52P5SI3iCEgZrgFevcDHuIwos40LjyMpgyMgZTiV2GW6H1cDzyTO5rF8pAazgJRhDHgnUUQP9/g1twKHjn/NunJiSaqSU3DKtgg4GXgNcDSxZc8iYmHBQ0TxfIu4mVRSi/x/pI20G7Wjx7YAAAAASUVORK5CYII=";
// maskedImage two
var mask2 = $(".container").mask({
maskImageUrl: maskedImageUrlb,
onMaskImageCreate: function(img) {
// add your style to the img example below
img.css({
"position": "fixed",
"left": 173,
"top": 1
})
}
});
fileupa2.onchange = function() {
mask2.loadImage(URL.createObjectURL(fileupa2.files[0]));
};
}); // end of document ready
// jq plugin for mask
(function($) {
var JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function(div) {},
}, options);
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.onDragStart = function(evt) {
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
var img = new Image();
img.src = 'https://www.what-dog.net/Images/faces2/scroll001.jpg';
evt.originalEvent.dataTransfer.setDragImage(img, 10, 10);
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
container.updateStyle();
}
};
container.updateStyle = function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.globalCompositeOperation = "source-over";
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({
"width": image.width,
"height": image.height
});
};
img = new Image();
img.src = settings.imageUrl;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}, 0);
};
// change the draggable image
container.loadImage = function(imageUrl) {
if (img)
img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle();
};
// change the masked Image
container.loadMaskImage = function(imageUrl, from) {
if (div)
div.remove();
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
div.find("canvas").on('dragstart', function(event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({
item: container,
id: settings.id
})
return container;
};
}(jQuery));
.container {
border: 1px solid #DDDDDD;
display: flex;
background: red;
width: 612px;
height: 612px;
}
.container canvas {
display: block;
}
.masked-img {
overflow: hidden;
margin-top: 50px;
position: relative;
}
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
image 2
<input id="fileupa2" type="file">
<div class="container">
</div>
Related
I am new to HTML and JS in general so I am currently lost on what I did wrong. I followed a tutorial by Chris Courses on Youtube (link: https://www.youtube.com/watch?v=4q2vvZn5aoo) until 1:27:13. The line of code was:
if (player.position.y > canvas.width){
console.log("you lose");
};
It worked perfectly for him, but I am not getting any console log nor any errors.
I tweaked a little bit of the code in order to fit the project that I need so I don't know if that's where I went wrong.
Here is my whole index.js:
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext('2d');
//adjust canvas width/height to take full screen
canvas.width= 1680;
canvas.height= 945;
//img function to easily import images
function img(file){
const image = new Image();
image.src = 'sprites/' +file;
return image;
}
//declaring images
const platformImg = img('platform.png');
const bg1 = img('bg1.png');
const bg2 = img('bg2.png');
const bg3 = img('bg3.png');
const bg4 = img('bg4.png');
const bg5 = img('bg5.png');
//Declaring variables
const gravity = 0.5; //Global Gravity
var firstSplash = 1;
var lastSplash = 210;
var splash = new Image;
var timer = setInterval( function(){
if (firstSplash>lastSplash){
clearInterval( timer );
}else{
splash.src = "./sprites/Splash/splash("+( firstSplash++ )+").jpg";
}
}, 1000/30 ); //Draw at 30 frames per second
class Player {
constructor(){ // Player Position/Width/Height
this.position = {
x: 100,
y: 100
}
this.velocity = { // Player Gravity
x: 0,
y: 0
}
this.width = 30;
this.height = 30;
}
// Make Player Visible
draw(){
ctx.fillStyle = 'red';
ctx.fillRect(this.position.x, this.position.y, this.width, this.height)
}
update(){
this.draw();
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
// Gravity to Player
if (this.position.y + this.height + this.velocity.y <= canvas.height)
this.velocity.y += gravity;
}
}
class Platform {
constructor({x, y, image}) {
this.position = {
x,
y
}
this.width = 600
this.height = 180
this.image = image
}
draw() {
ctx.drawImage(this.image, this.position.x, this.position.y)
}
}
class Decoration {
constructor({x, y, image}) {
this.position = {
x,
y
}
this.width = 16800
this.height = 945
this.image = image
}
draw() {
ctx.drawImage(this.image, this.position.x, this.position.y)
}
}
//Declaring variables
let player = new Player();
let platforms = [new Platform({
x: -1,
y: 800,
image: platformImg
}),
new Platform({
x: 600 -1,
y: 800,
image: platformImg
})]
let decorations = [
new Decoration({
x:0,
y:0,
image: bg1
}),
bg2Deco = new Decoration({
x:0,
y:0,
image: bg2
}),
bg3Deco = new Decoration({
x:0,
y:0,
image: bg3
}),
bg4Deco = new Decoration({
x:0,
y:0,
image: bg4
}),
bg5Deco = new Decoration({
x:0,
y:0,
image: bg5
})
]
const keys = {
right:{
pressed: false
},
left:{
pressed: false
}
}
//Levels
let level = 1
let levels = {
1: {
init: () => {
player = new Player();
platforms = [new Platform({
x: -1,
y: 800,
image: platformImg
}),
Platform({
x: 600 -1,
y: 800,
image: platformImg
})]
decorations = [
new Decoration({
x:0,
y:0,
image: bg1
}),
bg2Deco = new Decoration({
x:0,
y:0,
image: bg2
}),
bg3Deco = new Decoration({
x:0,
y:0,
image: bg3
}),
bg4Deco = new Decoration({
x:0,
y:0,
image: bg4
}),
bg5Deco = new Decoration({
x:0,
y:0,
image: bg5
})
]
}
}
}
// function drawSplash(){
// splash.onload = function(){
// ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height );
// ctx.drawImage(splash, 0, 0, ctx.canvas.width, ctx.canvas.height);
// };
// }
function gameStart(){
ctx.fillStyle = 'black'
ctx.fillRect(0,0,canvas.width, canvas.height)
document.getElementById("btnStart").remove();
player.draw();
animate();
}
function animate(){ // Animate
requestAnimationFrame(animate);
ctx.fillStyle = 'white';
ctx.fillRect(0,0,canvas.width, canvas.height)
decorations.forEach(Decoration =>{
Decoration.draw();
});
platforms.forEach(platform =>{
platform.draw();
});
player.update();
// Hold left/right for moving player
if (keys.right.pressed && player.position.x < 400){
player.velocity.x = 5
} else if (keys.left.pressed && player.position.x > 100) {
player.velocity.x = -5
} else {
player.velocity.x = 0
if (keys.right.pressed){
platforms.forEach(platform =>{
platform.position.x -=5
});
bg2Deco.position.x -= 3;
bg3Deco.position.x -= 4;
bg4Deco.position.x -= 5;
bg5Deco.position.x -= 6;
} else if (keys.left.pressed){
platforms.forEach(platform =>{
platform.position.x +=5
});
bg2Deco.position.x += 3;
bg3Deco.position.x += 4;
bg4Deco.position.x += 5;
bg5Deco.position.x += 6;
}
}
// Platform detection for player
platforms.forEach(platform =>{
if (player.position.y + player.height <= platform.position.y && player.position.y + player.height + player.velocity.y >= platform.position.y && player.position.x + player.width >= platform.position.x && player.position.x <= platform.position.x + platform.width) {
player.velocity.y = 0;
}
});
}
//lose condition
if (player.position.y > canvas.width){
console.log("you lose");
};
document.body.addEventListener('keydown', keyDown);
document.body.addEventListener('keyup', keyUp);
function keyDown(event){
if(event.code == "ArrowUp"){
if(event.repeat){return}
else player.velocity.y -= 10;
}
if(event.code == "ArrowLeft"){
keys.left.pressed = true;
}
if(event.code == "ArrowRight"){
keys.right.pressed = true;
}
}
function keyUp(event){
if(event.code == "ArrowUp"){
player.velocity.y -= 10;
}
if(event.code == "ArrowLeft"){
keys.left.pressed = false;
}
if(event.code == "ArrowRight"){
keys.right.pressed = false;
}
}
player.draw();
animate();
//drawSplash();
I feel like I'm being an idiot and missing something trivial. Any help is appreciated! Thank you!
It was confirmed that the function did not work properly.
The "you loose" if statement was outside.
Check yours animate function indent plz.
function animate() { // Animate
requestAnimationFrame(animate);
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height)
decorations.forEach(Decoration => {
Decoration.draw();
});
platforms.forEach(platform => {
platform.draw();
});
player.update();
// Hold left/right for moving player
if (keys.right.pressed && player.position.x < 400) {
player.velocity.x = 5
} else if (keys.left.pressed && player.position.x > 100) {
player.velocity.x = -5
} else {
player.velocity.x = 0
if (keys.right.pressed) {
platforms.forEach(platform => {
platform.position.x -= 5
});
bg2Deco.position.x -= 3;
bg3Deco.position.x -= 4;
bg4Deco.position.x -= 5;
bg5Deco.position.x -= 6;
} else if (keys.left.pressed) {
platforms.forEach(platform => {
platform.position.x += 5
});
bg2Deco.position.x += 3;
bg3Deco.position.x += 4;
bg4Deco.position.x += 5;
bg5Deco.position.x += 6;
}
}
// Platform detection for player
platforms.forEach(platform => {
if (player.position.y + player.height <= platform.position.y && player.position.y + player.height + player.velocity.y >= platform.position.y && player.position.x + player.width >= platform.position.x && player.position.x <= platform.position.x + platform.width) {
player.velocity.y = 0;
}
});
//lose condition
// Check here.
if (player.position.y > canvas.width) {
console.log("you lose");
}
}
I have two canvas first canvas is original size second canvas is twice bigger. At the same time i drawing on the both canvas, but on the second canvas i draw twice bigger elements it's looks like on zoomed first canvas.
How look like:
Problem is when i try redraw from big canvas to small canvas i got my paintings a little brighter, but only brighter is where use pencil:
smallCtx.clearRect(0, 0, smallCanvas.width, smallCanvas.height);
smallCtx.drawImage(bigCanvas, 0, 0, paperFullWidth, paperFullHeight);
Full code:
$(document).ready(function() {
function Pencil(smallCtx, bigCtx, size, color, opacity, moreTimes) {
this.init(smallCtx, bigCtx, size, color, opacity, moreTimes);
}
Pencil.prototype = {
smallCtx: null, moreTimes: null,
prevMouseX: null, prevMouseY: null,
moreTimes: 1,
color: '0, 0, 0',
opacity: 1,
init: function(smallCtx, bigCtx, size, color, opacity, moreTimes) {
this.smallCtx = smallCtx;
this.bigCtx = bigCtx;
this.setSize(size);
this.setColor(color);
this.setOpacity(opacity);
this.moreTimes = moreTimes;
},
stroke: function(mouseX, mouseY, scale) {
/* in first canvas drawing */
this.smallCtx.beginPath();
this.smallCtx.moveTo(this.prevMouseX, this.prevMouseY);
this.smallCtx.lineTo(mouseX, mouseY);
this.smallCtx.closePath();
this.smallCtx.stroke();
/* in second canvas drawing scaled */
this.bigCtx.lineWidth = this.smallCtx.lineWidth * this.moreTimes;
this.bigCtx.beginPath();
this.bigCtx.moveTo( this.prevMouseX * this.moreTimes, this.prevMouseY * this.moreTimes);
this.bigCtx.lineTo( mouseX * this.moreTimes, mouseY * this.moreTimes );
this.bigCtx.closePath();
this.bigCtx.stroke();
this.move(mouseX, mouseY);
},
move: function(mouseX, mouseY) {
this.prevMouseX = mouseX;
this.prevMouseY = mouseY;
},
/* GETTERS */
getSize: function() {
return this.smallCtx.lineWidth;
},
getColor: function() {
return this.color;
},
getOpacity: function() {
return this.opacity;
},
/* SETTERS */
setSize: function(size) {
this.smallCtx.lineWidth = size;
},
setColor: function(color) {
this.color = color; //rgb like: 255,0,0
this.bigCtx.shadowBlur = this.smallCtx.shadowBlur = 0;
this.setStrokeStyle();
},
setOpacity: function(opacity) {
this.opacity = opacity;
this.setStrokeStyle();
},
setStrokeStyle: function() {
this.bigCtx.strokeStyle = this.smallCtx.strokeStyle =
this.bigCtx.fillStyle = this.smallCtx.fillStyle = 'rgba(' + this.getColor() + ', ' + this.getOpacity() +')';
},
}
var smallCanvas = document.getElementById("smallCanvas");
var smallCtx = smallCanvas.getContext("2d");
var bigCanvas = document.getElementById("bigCanvas");
var bigCtx = bigCanvas.getContext("2d");
var paperFullWidth = 150;
var paperFullHeight = 150;
var moreTimes = 2;
var scale = 100;
smallCanvas.width = paperFullWidth;
smallCanvas.height = paperFullHeight;
bigCanvas.width = paperFullWidth * moreTimes;
bigCanvas.height = paperFullHeight * moreTimes;
fillCanvas('rgba(255,255,255,1)');
drawSquare(); //draw a square
pencil = new Pencil(smallCtx, bigCtx, 1, "0,0,0", 0.3, moreTimes);
pointerPos = {}; //for pointer position
var isCanDraw = false;
/****** MOUSE EVENTS FOR CANVAS ******/
$('#smallCanvas').on('mousedown', function(e) {
pointerPos = getMousePos(smallCanvas, e);
isCanDraw = true;
pencil.move(pointerPos.x, pointerPos.y);
});
$('#smallCanvas').on('mouseup', function(e) {
pointerPos = getMousePos(smallCanvas, e);
isCanDraw = false;;
});
$('#smallCanvas').on('mousemove', function(e) {
if(isCanDraw) {
pointerPos = getMousePos(smallCanvas, e);
pencil.stroke( pointerPos.x, pointerPos.y, scale );
}
});
$('#redraw').click(function() {
smallCtx.clearRect(0, 0, smallCanvas.width, smallCanvas.height);
smallCtx.drawImage(bigCanvas, 0, 0, paperFullWidth, paperFullHeight);
});
function fillCanvas(color) {
var tempFillStyle = smallCtx.fillStyle;
bigCtx.fillStyle = smallCtx.fillStyle = color;
smallCtx.fillRect(0, 0, smallCanvas.width, smallCanvas.height);
bigCtx.fillRect(0, 0, bigCanvas.width, bigCanvas.height);
bigCtx.fillStyle = smallCtx.fillStyle = tempFillStyle;
}
function getMousePos(canvas, evt) {
evt = evt.originalEvent || window.event || evt;
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function drawSquare() {
smallCtx.fillStyle = bigCtx.fillStyle = 'rgba(0,0,0,0.3)';
smallCtx.fillRect(0,0,60,60);
bigCtx.fillRect(0,0,60*moreTimes,60*moreTimes);
}
});
*{
background-color:#CECECE;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id='smallCanvas' style='z-index: 1;'></canvas>
<canvas id="bigCanvas"></canvas>
<input type='button' id='redraw' value='Redraw'>
You are making the context.lineWidth twice as wide on the big canvas by setting moreTimes=2.
That makes the stroke on the bigger canvas appear darker.
I have a kineticjs canvas with image upload and text input, both functions are working fine but I can't get the image resize anchors to show... I need to get the image resize anchors to show "onClick" of the image.
any help is much appreciated :)
thanks in advance.
here is the js
var stage = new Kinetic.Stage({
container: 'container',
width: 375,
height: 200
});
var layer = new Kinetic.Layer();
//image loader
var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
layer.add(new Kinetic.Image({
x: 100,
y: 50,
image: img,
width: 200,
height: 130,
draggable: true
}));
text.moveToTop();
stage.draw();
};
console.log(event);
img.src = event.target.result;
};
reader.readAsDataURL(e.target.files[0]);
}
// parameters
var resizerRadius = 3;
var rr = resizerRadius * resizerRadius;
// constant
var pi2 = Math.PI * 2;
function draw(img, withAnchors, withBorders) {
// clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// draw the image
var view = img.view;
ctx.drawImage(img, 0, 0, img.width, img.height, view.left, view.top, view.width, view.height);
// optionally draw the draggable anchors
if (withAnchors) {
drawDragAnchor(view.left, view.top);
drawDragAnchor(view.left + view.width, view.top);
drawDragAnchor(view.left + view.width, view.top + view.height);
drawDragAnchor(view.left, view.top + view.height);
}
// optionally draw the connecting anchor lines
if (withBorders) {
ctx.beginPath();
ctx.rect(view.left, view.top, view.width, view.height);
ctx.stroke();
}
drawText();
}
function drawDragAnchor(x, y) {
ctx.beginPath();
ctx.arc(x, y, resizerRadius, 0, pi2, false);
ctx.closePath();
ctx.fill();
}
function drawText(){
var x = 40,
y = 100;
ctx.font = "bold 20px sans-serif";
ctx.fillStyle = "black";
ctx.fillText($("#textBox").val(), x, y);
}
// -------------------------------------------
// - Hit Testing -
// -------------------------------------------
// return 0,1,2, or 3 if (x,y) hits the respective anchor
// of the given view.
// return -1 if no anchor hit.
function anchorHitTest(view, x, y) {
var dx, dy;
x -= view.left;
y -= view.top;
// top-left
dx = x;
dy = y;
if (dx * dx + dy * dy <= rr) return (0);
// top-right
dx = x - view.width;
dy = y;
if (dx * dx + dy * dy <= rr) return (1);
// bottom-right
dx = x - view.width;
dy = y - view.height;
if (dx * dx + dy * dy <= rr) return (2);
// bottom-left
dx = x;
dy = y - view.height;
if (dx * dx + dy * dy <= rr) return (3);
return (-1);
}
// return true if (x,y) lies within the view
function hitImage(view, x, y) {
x -= view.left;
y -= view.top;
return (x > 0 && x < view.width && y > 0 && y < view.height);
}
// -------------------------------------------
// - Mouse -
// -------------------------------------------
var mousePos = {
x: 0,
y: 0
};
var draggingImage = false;
var startX, startY;
var isDown = false;
var currentImg = null;
var draggingResizer;
function updateMousePos(e) {
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
updateMousePos = function (e) {
mousePos.x = parseInt(e.clientX - offsetX);
mousePos.y = parseInt(e.clientY - offsetY);
};
return updateMousePos(e);
}
function handleMouseDown(e) {
updateMousePos(e);
// here you could make a loop to see which image / anchor was clicked
draggingResizer = anchorHitTest(img.view, mousePos.x, mousePos.y);
draggingImage = draggingResizer < 0 && hitImage(img.view, mousePos.x, mousePos.y);
//
if (draggingResizer<0 && !draggingImage) return;
startX = mousePos.x;
startY = mousePos.y;
currentImg = img;
}
function handleMouseUp(e) {
if (!currentImg) return;
draggingResizer = -1;
draggingImage = false;
draw(currentImg, true, false);
currentImg = null;
}
function handleMouseOut(e) {
handleMouseUp(e);
}
function handleMouseMove(e) {
if (!currentImg) return;
updateMousePos(e);
var view = currentImg.view;
if (draggingResizer > -1) {
var oldView = {
left: view.left,
top: view.top,
width: view.width,
height: view.height
};
// resize the image
switch (draggingResizer) {
case 0:
cl('ttoo');
//top-left
view.left = mousePos.x;
view.top = mousePos.y;
view.width = oldView.left + oldView.width - mousePos.x;
view.height = oldView.top + oldView.height - mousePos.y;
break;
case 1:
//top-right
// view.left unchanged
view.top = mousePos.y;
view.width = mousePos.x - oldView.left;
view.height = oldView.top + oldView.height - mousePos.y;
break;
case 2:
//bottom-right
view.width = mousePos.x - oldView.left;
view.height = mousePos.y - oldView.top;
break;
case 3:
//bottom-left
view.left = mousePos.x;
view.width = oldView.left + oldView.width - mousePos.x;
view.height = mousePos.y - (oldView.top);
break;
}
if (view.width < 25) view.width = 25;
if (view.height < 25) view.height = 25;
// redraw the image with resizing anchors
draw(currentImg, true, true);
} else if (draggingImage) {
imageClick = false;
// move the image by the amount of the latest drag
var dx = mousePos.x - startX;
var dy = mousePos.y - startY;
view.left += dx;
view.top += dy;
// reset the startXY for next time
startX = mousePos.x;
startY = mousePos.y;
// redraw the image with border
draw(currentImg, false, true);
}
}
var text = new Kinetic.Text({
x: 20,
y: 30,
text: '',
fontSize: '30',
fontFamily: 'Calibri',
fill: 'black',
draggable: true
});
stage.add(layer);
layer.add(text);
document.getElementById("textBox").addEventListener("keyup", function () {
text.setText(this.value);
layer.draw();
}, true);
document.getElementById("textSize").addEventListener("change", function () {
var size = this.value;
text.fontSize(size);
layer.draw();
}, true);
document.getElementById("fontFamily").addEventListener("change", function () {
var font = this.value;
text.fontFamily(font);
layer.draw();
}, true);
document.getElementById("fontStyle").addEventListener("change", function () {
var style = this.value;
text.fontStyle(style);
layer.draw();
}, true);
document.getElementById("fill").addEventListener("change", function () {
var colour = this.value;
text.fill(colour);
layer.draw();
}, true);
$("#canvas").mousedown(function (e) {
handleMouseDown(e);
});
$("#canvas").mousemove(function (e) {
handleMouseMove(e);
});
$("#canvas").mouseup(function (e) {
handleMouseUp(e);
});
$("#canvas").mouseout(function (e) {
handleMouseOut(e);
});
// utility
function cl() {
console.log.apply(console, arguments);
}
can provide jsFiddle if needed :)
You're trying to mix KineticJS with html canvas drawing commands.
That combination doesn't work because KineticJS does its magic by taking over the canvas--leaving no ability to call native canvas commands like context.beginPath.
// these 2 don't play together
... new Kinetic.Image ...
... ctx.beginPath ...
Anyway, Here's the answer to your question (in case you choose KineticJS for your project)
Kinetic.Image can be asked to execute a function when the image is clicked like this:
var image=new Kinetic.Image({
x: 100,
y: 50,
image: img,
width: 200,
height: 130,
draggable: true
}));
image.on("click",function(){
// The image was clicked
// Show your anchors now
});
layer.add(image);
[ Addition: Example of Kinetic.Image resizing ]
I don't like the overhead and complexity of maintaining anchors to resize Kinetic.Images.
Here's an example that lets you drag on the right side of the image to scale it proportionally:
http://jsfiddle.net/m1erickson/p8bpC/
You could modify this code to add cosmetic resizing grabbers (the grabbers are not necessary, but if you prefer the "anchor" look, you can add them).
You can refer to this question, the answers are guided and constructive, and contain a jsfiddle with the exact same behavior that you need.
Kinetic JS - how do you hide all the anchors for a given group ID
I am already using jQuery plugin called jCrop but recently I discovered KinectJs and it really solves many problems for me. Then I stumbled upon this example:
http://www.html5canvastutorials.com/labs/html5-canvas-drag-and-drop-resize-and-invert-images/
And I decided to write my own cropping rectangle based on KinectJs and above example.
function update(activeAnchor) {
var group = activeAnchor.getParent();
var topLeft = group.get('.topLeft')[0];
var topRight = group.get('.topRight')[0];
var bottomRight = group.get('.bottomRight')[0];
var bottomLeft = group.get('.bottomLeft')[0];
var cropper = group.get('.cropper')[0];
var leftMask = group.getParent().get('.leftMask')[0];
var rightMask = group.getParent().get('.rightMask')[0];
var topMask = group.getParent().get('.topMask')[0];
var bottomMask = group.getParent().get('.bottomMask')[0];
var anchorX = activeAnchor.getX();
var anchorY = activeAnchor.getY();
// update anchor positions
switch (activeAnchor.getName()) {
case 'topLeft':
topRight.setY(anchorY);
bottomLeft.setX(anchorX);
updateLeftMaskWidth(leftMask,activeAnchor);
updateTopMaskHeight(topMask,cropper,activeAnchor);
break;
case 'topRight':
topLeft.setY(anchorY);
bottomRight.setX(anchorX);
updateRightMaskWidthAndPos(rightMask,activeAnchor);
updateTopMaskHeight(topMask,cropper,activeAnchor);
break;
case 'bottomRight':
bottomLeft.setY(anchorY);
topRight.setX(anchorX);
updateRightMaskWidthAndPos(rightMask,activeAnchor);
updateBottomMaskHeightAndPos(bottomMask,cropper,activeAnchor);
break;
case 'bottomLeft':
bottomRight.setY(anchorY);
topLeft.setX(anchorX);
updateLeftMaskWidth(leftMask,activeAnchor);
updateBottomMaskHeightAndPos(bottomMask,cropper,activeAnchor);
break;
}
cropper.setPosition(topLeft.getPosition().x,topLeft.getPosition().y);
var width = topRight.getX() - topLeft.getX();
var height = bottomLeft.getY() - topLeft.getY();
if(width && height) {
cropper.setSize(width, height);
}
}
function updateLeftMaskWidth(mask,leftAnchor) {
mask.setWidth(leftAnchor.getAbsolutePosition().x - 100);
}
function updateRightMaskWidthAndPos(mask,rightAnchor) {
mask.setAbsolutePosition(rightAnchor.getAbsolutePosition().x,mask.getAbsolutePosition().y);
mask.setWidth(213 - (rightAnchor.getAbsolutePosition().x - 100));
}
function updateTopMaskHeight(mask,cropper,topAnchor) {
mask.setAbsolutePosition(topAnchor.getAbsolutePosition().x,mask.getAbsolutePosition().y);
mask.setHeight(topAnchor.getAbsolutePosition().y - 110);
mask.setWidth(cropper.getWidth());
}
function updateBottomMaskHeightAndPos(mask,cropper,bottomAnchor) {
mask.setAbsolutePosition(bottomAnchor.getAbsolutePosition().x, bottomAnchor.getAbsolutePosition().y);
mask.setHeight(236 - (bottomAnchor.getAbsolutePosition().y - 110));
mask.setWidth(cropper.getWidth());
}
function addAnchor(group, x, y, name) {
var stage = group.getStage();
var layer = group.getLayer();
var anchor = new Kinetic.Circle({
x: x,
y: y,
stroke: '#666',
fill: '#ddd',
strokeWidth: 1,
radius: 5,
name: name,
draggable: true,
dragBoundFunc: function(pos) {
var newX = pos.x;
var newY = pos.y;
var image = this.getParent().getParent().get('.image')[0];
var cropper = this.getParent();
// Bound horizontally
if(newX < 100) {
newX = 100;
}
else if(newX > image.getWidth() + 100 - cropper.getWidth()) {
newX = image.getWidth() + 100 - cropper.getWidth();
}
if(newY < 110) {
newY = 110;
}
else if(newY > image.getHeight() + 110 - cropper.getHeight()) {
newY = image.getHeight() + 110 - cropper.getHeight();
}
return {
x: newX,
y: newY
}
}
});
anchor.on('dragmove', function() {
update(this);
layer.draw();
});
// add hover styling
anchor.on('mouseover', function() {
var layer = this.getLayer();
document.body.style.cursor = 'pointer';
this.setStrokeWidth(2);
layer.draw();
});
anchor.on('mouseout', function() {
var layer = this.getLayer();
document.body.style.cursor = 'default';
this.setStrokeWidth(2);
layer.draw();
});
group.add(anchor);
}
function initStage(img) {
var stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 400
});
var imageGroup = new Kinetic.Group({
x: 100,
y: 110
});
var leftMaskGroup = new Kinetic.Group({
x: 100,
y: 110
});
var rightMaskGroup = new Kinetic.Group({
x: 270,
y: 110
});
var topMaskGroup = new Kinetic.Group({
x: 169.9,
y: 110
});
var bottomMaskGroup = new Kinetic.Group({
x: 169.9,
y: 150+138
});
var cropperGroup = new Kinetic.Group({
x: 170,
y: 150,
draggable: true,
dragBoundFunc: function(pos) {
var newX = pos.x;
var newY = pos.y;
var image = this.getParent().get('.image')[0];
var cropper = this.get('.cropper')[0];
// Bound horizontally
if(newX < 100) {
newX = 100;
}
else if(newX > image.getWidth() + 100 - cropper.getWidth()) {
newX = image.getWidth() + 100 - cropper.getWidth();
}
// Bound vertically
if(newY < 110) {
newY = 110;
}
else if(newY > image.getHeight() + 110 - cropper.getHeight()) {
newY = image.getHeight() + 110 - cropper.getHeight();
}
return {
x: newX,
y: newY
}
}
});
var layer = new Kinetic.Layer();
/*
* go ahead and add the groups
* to the layer and the layer to the
* stage so that the groups have knowledge
* of its layer and stage
*/
layer.add(imageGroup);
layer.add(leftMaskGroup);
layer.add(rightMaskGroup);
layer.add(topMaskGroup);
layer.add(bottomMaskGroup);
layer.add(cropperGroup);
stage.add(layer);
// cropping rectangle
var cropperRect = new Kinetic.Rect({
x: 0,
y: 0,
width: 100,
height: 138,
stroke: 'black',
name: 'cropper',
strokeWidth: 1
});
cropperGroup.add(cropperRect);
addAnchor(cropperGroup, 0, 0, 'topLeft');
addAnchor(cropperGroup, 100, 0, 'topRight');
addAnchor(cropperGroup, 100, 138, 'bottomRight');
addAnchor(cropperGroup, 0, 138, 'bottomLeft');
cropperGroup.on('dragstart', function() {
this.moveToTop();
});
cropperGroup.on('dragmove', function() {
var layer = this.getLayer();
var topLeft = this.get('.topLeft')[0];
var bottomLeft = this.get('.bottomLeft')[0];
var topRight = this.get('.topRight')[0];
var leftMask = this.getParent().get('.leftMask')[0];
var rightMask = this.getParent().get('.rightMask')[0];
var topMask = this.getParent().get('.topMask')[0];
var bottomMask = this.getParent().get('.bottomMask')[0];
updateLeftMaskWidth(leftMask,topLeft);
updateRightMaskWidthAndPos(rightMask,topRight);
updateTopMaskHeight(topMask,this.get('.cropper')[0],topLeft);
updateBottomMaskHeightAndPos(bottomMask,this.get('.cropper')[0],bottomLeft);
layer.draw();
});
// left mask
var leftMaskRect = new Kinetic.Rect({
x: 0,
y: 0,
width: 70,
height: 236,
fill: 'black',
name: 'leftMask',
strokeWidth: 0,
opacity: 0.5
});
leftMaskGroup.add(leftMaskRect);
// right mask
var rightMaskRect = new Kinetic.Rect({
x: 0,
y: 0,
width: 213-170,
height: 236,
fill: 'black',
name: 'rightMask',
strokeWidth: 0,
opacity: 0.5
});
rightMaskGroup.add(rightMaskRect);
// top mask
var topMaskRect = new Kinetic.Rect({
x: 0,
y: 0,
width: 100.2,
height: 150-110,
fill: 'black',
name: 'topMask',
strokeWidth: 0,
opacity: 0.5
});
topMaskGroup.add(topMaskRect);
// bottom mask
var bottomMaskRect = new Kinetic.Rect({
x: 0,
y: 0,
width: 100.2,
height: 236-138-(150-110),
fill: 'black',
name: 'bottomMask',
strokeWidth: 0,
opacity: 0.5
});
bottomMaskGroup.add(bottomMaskRect);
// image
var srcImg = new Kinetic.Image({
x: 0,
y: 0,
image: img,
name: 'image'
});
imageGroup.add(srcImg);
stage.draw();
}
var img = new Image();
img.onload = function() {
initStage(this);
}
img.src = 'http://www.html5canvastutorials.com/demos/assets/yoda.jpg';
It works almost perfectly. The problem is that when you resize using the circle anchors and after a few tries (just give it a few shots) when you try to drag the whole rectangle it allows you to drag it out of bounds !
From my debugging this seems like an issue with the library but if sb. sees the problem in my code or sees a way to optimize it please share your thoughts.
The result of my effort can be seen here:
http://jsfiddle.net/wanderer/WLpXF/
A) Reproducing the bug:
Drag a top anchor upwards (say it was dragged N pixels)
Drag the entire cropper upwards; it can leave the image boundaries by N pixels
Similar behaviour for the other anchors and directions.
B) The solution:
Add this function to the script:
function readjust() {
var group = this.getParent();
var topLeft = group.get('.topLeft')[0];
var topRight = group.get('.topRight')[0];
var bottomRight = group.get('.bottomRight')[0];
var bottomLeft = group.get('.bottomLeft')[0];
var cropper = group.get('.cropper')[0];
var tlx = cropper.getX(),
tly = cropper.getY(),
w = cropper.getWidth(),
h = cropper.getHeight();
group.setX(group.getX() + tlx);
group.setY(group.getY() + tly);
topLeft.setPosition(0,0);
topRight.setPosition(w,0);
bottomLeft.setPosition(0,h);
bottomRight.setPosition(w,h);
cropper.setPosition(0,0);
}
And the following handler in addAnchor():
anchor.on('dragend', readjust);
Fiddle: http://jsfiddle.net/BMy7b/1/
Alternatively the code from readjust() can be included in update(), as suggested by MarmiK. This would run more operations on every drag thus might be slower (but I am not sure; opinions?). Fiddle: http://jsfiddle.net/vUPeQ/1/
The problem was that the cropper and anchors moved relatively to the cropperGroup, but the cropperGroup drag bounding function wasn't taking it into account.
Have fun!
One quick update: I was after something like this (nice looking cropping rectangle), but when I try this code with the latest KineticJS 5.0.1, well, it does a couple of nasty things. You can see by yourselves here: [http://jsfiddle.net/vUPeQ/2/]:http://jsfiddle.net/vUPeQ/2/
My wild guess is that it's because some api changes, but I can't find which one...
Can anyone give a hand over here?
Thanks so much!!!
I'm having trouble keeping one object on my canvas. The initially drawn box rendered it in the correct position, but it disappears when I drag it:
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
eraseAllButton = document.getElementById('eraseAllButton'),
strokeStyleSelect = document.getElementById('strokeStyleSelect'),
guidewireCheckbox = document.getElementById('guidewireCheckbox'),
drawingSurfaceImageData,
mousedown = {},
rubberbandRect = {},
dragging = false,
guidewires = guidewireCheckbox.checked,
w = 90, h = 90;
count = 0;
boxesXCo = 0;
boxesYCo = 0;
i = 0;
// Functions..........................................................
function drawGrid(color, stepx, stepy) {
context.save()
context.strokeStyle = color;
context.lineWidth = 0.5;
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
for (var i = stepx + 0.5; i < context.canvas.width; i += stepx) {
context.beginPath();
context.moveTo(i, 0);
context.lineTo(i, context.canvas.height);
context.stroke();
}
for (var i = stepy + 0.5; i < context.canvas.height; i += stepy) {
context.beginPath();
context.moveTo(0, i);
context.lineTo(context.canvas.width, i);
context.stroke();
}
context.restore();
}
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect();
return { x: x - bbox.left * (canvas.width / bbox.width),
y: y - bbox.top * (canvas.height / bbox.height) };
}
// Save and restore drawing surface...................................
function saveDrawingSurface() {
drawingSurfaceImageData = context.getImageData(0, 0,
canvas.width,
canvas.height);
}
function restoreDrawingSurface() {
context.putImageData(drawingSurfaceImageData, 0, 0);
}
function drawRubberbandShape(loc) {
context.beginPath();
context.moveTo(mousedown.x, mousedown.y);
//context.lineTo(loc.x, loc.y);
context.stroke();
}
function updateRubberband(loc) {
//updateRubberbandRectangle(loc);
context.restore();
drawRubberbandShape(loc);
}
// Guidewires.........................................................
function drawHorizontalLine (y) {
context.beginPath();
context.moveTo(0,y+0.5);
context.lineTo(context.canvas.width,y+0.5);
context.stroke();
}
function drawVerticalLine (x) {
context.beginPath();
context.moveTo(x+0.5,0);
context.lineTo(x+0.5,context.canvas.height);
context.stroke();
}
function drawGuidewires(x, y) {
context.save();
context.strokeStyle = 'rgba(0,0,230,0.4)';
context.lineWidth = 0.5;
drawVerticalLine(x);
drawHorizontalLine(y);
context.restore();
}
// Canvas event handlers..............................................
canvas.onmousedown = function (e) {
var loc = windowToCanvas(e.clientX, e.clientY);
e.preventDefault(); // prevent cursor change
context.restore();
saveDrawingSurface();
mousedown.x = loc.x;
mousedown.y = loc.y;
dragging = true;
if (i ==0)
i++;
else if(((mousedown.x<=(boxesXCo+w)&&(mousedown.x>=boxesXCo))&&
((mousedown.y<=(boxesYCo+h)&&(mousedown.y>=boxesYCo)))))
i--;
};
canvas.onmousemove = function (e) {
var loc;
if (dragging) {
e.preventDefault(); // prevent selections
loc = windowToCanvas(e.clientX, e.clientY);
restoreDrawingSurface();
//updateRubberband(loc);
if(guidewires) {
drawGuidewires(loc.x, loc.y);
}
}
if(((mousedown.x<=(boxesXCo+w)&&(mousedown.x>=boxesXCo))&&
((mousedown.y<=(boxesYCo+h)&&(mousedown.y>=boxesYCo))))
&& (dragging)&&(i == 1 )){
context.restore();
restoreDrawingSurface();
context.fillStyle = strokeStyleSelect.value;
context.fillRect(e.clientX,e.clientY,w,h);
};
//Trying to implement moving shapes but need to store values of drawn objs
};
canvas.onmouseup = function (e) {
loc = windowToCanvas(e.clientX, e.clientY);
restoreDrawingSurface();
updateRubberband(loc);
dragging = false;
if(i == 0);
else {
saveDrawingSurface();
restoreDrawingSurface();
context.fillRect(e.clientX,e.clientY, w, h);
boxesXCo = e.clientX;
boxesYCo = e.clientY;
context.restore();
i++;}
/*else if(i == 1)
{
context.restore();
}*/
//context.fillRect(mousedown.x,mousedown.y,w,h,"FF0982");
};
// Controls event handlers.......................................
eraseAllButton.onclick = function (e) {
context.clearRect(0, 0, canvas.width, canvas.height);
drawGrid('lightgray', 10, 10);
saveDrawingSurface();
count =0;
context.restore();
};
strokeStyleSelect.onchange = function (e) {
context.strokeStyle = strokeStyleSelect.value;
context.fillStyle = strokeStyleSelect.value;
};
guidewireCheckbox.onchange = function (e) {
guidewires = guidewireCheckbox.checked;
};
// Initialization................................................
context.strokeStyle = strokeStyleSelect.value;
context.fillStyle = strokeStyleSelect.value;
drawGrid('lightgray', 10, 10);
//context.fillRect(mousedown.x,mousedown.y,(mousedown.x+50),(mousedown.x+50),"FF0982");
//context.drawRect(mousedown.x-50,mousedown.y-50,mousedown.x+50,mousedown.y+50);
thanx again
Rather than drawing to canvas on each mouse movement, use window.requestFrameAnimation to draw constantly.
At a guess, I'd assume either the browser rendering is interfering or the coordinates are out but I can't run your code to make sure.
I've written some pseudo code that shows what I do for rendering things. You'll need to implement this for yourself, it won't run out of the box, it's just intended as a guide.
var Box = function() {
};
Box.prototype = {
x: 0,
y: 0,
draw: function (canvas) {
// draw the item on the canvas
}
};
var box = new Box();
window.requestAnimationFrame(function() {
box.draw(canvas);
window.requestAnimationFrame();
});
canvas.onmousemove = function(e) {
if (dragging) {
box.x = e.clientX;
box.y = e.clientY;
}
}