resize canvas and merge - angularjs

hi i need to create an ionic app to draw on image or pdf.
I need to drag the canvas where i want on the image, draw on it, resize it and save in another image wich is the result of the old one plus the draw canvas.
canvas is like this, now i can drag or i can draw, but i'm not capable to set 4 anchor on the edge of canvas to resize it
canvas ion-pinch overflow-scroll="false" id='signatureCanvas' on-drag="true" width="200" height="300" style='border: 1px solid black; background-color: transparent;'
the directive to drag
.directive('ionPinch', function($timeout,$ionicGesture) {
return {
restrict: 'A',
link: function($scope, $element) {
$timeout(function() {
var canvas = $element[0],
posX = 0,
posY = 0,
lastPosX = 0,
lastPosY = 0,
bufferX = 0,
bufferY = 0,
scale = 1,
lastScale,
rotation = 0,
last_rotation, dragReady = 0;
ionic.onGesture('touch drag transform dragend', function(e) {
e.gesture.srcEvent.preventDefault();
e.gesture.preventDefault();
switch (e.type) {
case 'touch':
lastScale = scale;
last_rotation = rotation;
break;
case 'drag':
posX = e.gesture.deltaX + lastPosX;
posY = e.gesture.deltaY + lastPosY;
break;
case 'transform':
rotation = e.gesture.rotation + last_rotation;
scale = e.gesture.scale * lastScale
break;
case 'dragend':
lastPosX = posX;
lastPosY = posY;
lastScale = scale;
break;
}
var transform =
"translate3d(" + posX + "px," + posY + "px, 0) " +
"scale(" + scale + ")" +
"rotate(" + rotation + "deg) ";
e.target.style.transform = transform;
e.target.style.webkitTransform = transform;
}, $element[0]);
});
}
};
})
and the controller to draw
ratio = 1.0;
$scope.dev_width = $window.innerWidth;
$scope.dev_height = $window.innerHeight;
var dev_width = $window.innerWidth;
var dev_height = $window.innerHeight;
console.log(dev_width);
var canvas = document.getElementById('signatureCanvas');
var context = canvas.getContext('2d');
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = canvas.offsetWidth * ratio;
canvas.height = canvas.offsetHeight * ratio;
canvas.getContext('2d').scale(ratio, ratio);
}
resizeCanvas();
var signaturePad = new SignaturePad(canvas);
$scope.clearCanvas = function() {
signaturePad.clear();
}

Related

Why is the array undefined even though I pushed a value in it?

I have this function type() where I define an array texts and I add some values to it and then I set the local texts array to the state array, so it'll be accessible for other functions as well.
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
And this is the state:
state ={
texts:[]
}
I check with the alert() what's the index of 0 of the array to see if it's working, however it says it's undefined:
alert(this.state.texts[0])
This is my whole function:
type()
{
var canvas = document.getElementById('board'),
ctx = canvas.getContext('2d'),
font = '20px sans-serif',
hasInput = false;
var sketch = document.querySelector('#sketch');
var sketch_style = getComputedStyle(sketch);
canvas.width = parseInt(sketch_style.getPropertyValue('width'));
canvas.height = parseInt(sketch_style.getPropertyValue('height'));
var texts = [];
texts.push("Hello", 20, 20)
this.setState({texts: texts})
alert(this.state.texts[0])
ctx.font = font
ctx.fillText("rrwerwewewrewrwerwe", 50, 50)
canvas.onclick = function(e) {
if (hasInput) return;
addInput(e.clientX, e.clientY);
}
//Function to dynamically add an input box:
function addInput(x, y) {
var input = document.createElement('input');
input.type = 'text';
input.style.position = 'fixed';
input.style.left = (x - 4) + 'px';
input.style.top = (y - 4) + 'px';
input.onkeydown = handleEnter;
document.body.appendChild(input);
input.focus();
hasInput = true;
}
//Key handler for input box:
function handleEnter(e) {
var keyCode = e.keyCode;
if (keyCode === 13) {
addText(this.value, parseInt(this.style.left, 10), parseInt(this.style.top, 10));
document.body.removeChild(this);
hasInput = false;
}
}
//Draw the text onto canvas:
function addText(text, x, y) {
ctx.position = 'absolute';
ctx.font = font;
ctx.fillText(text, x, y);
}
}

React client tries to access server resource without access to it gets 404

I believe my react code is trying to access a server directory after its compiled and sent to the client. This means when it looks for the gameLogic.js and style.css files it cant locate them. I'm wondering how I would go about getting the react component im working on to get a copy of them and send them off to the remote client. I get the following errors.
pages/game.js
import * as React from "react";
import Layout from "../components/Layout";
import Separator from "../components/Separator";
import CanvasCanvas from "../components/CanvasCanvas";
export default class extends React.Component {
render() {
return (
<Layout>
<main>
<div className="loginBox5">
<Separator height={50}/>
<div className="center">
<h1>Game Play:</h1>
<Separator height={50}/>
<div id="PlayAreaImg" className="gameContainer">
<CanvasCanvas id={"Memes"}/>
</div>
</div>
<Separator height={350}/>
</div>
</main>
</Layout>
)
}
}
src/gameLogic.js
var keyState = {};
window.addEventListener('keydown',function(e){
keyState[e.keyCode || e.which] = true;
},true);
window.addEventListener('keyup',function(e){
keyState[e.keyCode || e.which] = false;
},true);
x = 100;
function drawObj(ctx, object){
var x = object[0];
var y = object[1];
var wid = object[2];
var hei = object[3];
var r = object[4];
var g = object[5];
var b = object[6];
var t = object[7];
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
ctx.fillStyle = "rgba("+String(r)+","+String(g)+","+String(b)+","+String(t)+")"; // colour ball
ctx.fillRect (x, y, wid, hei); // render ball
return ctx;
}
function renderAll(objects){
console.log("### - Render: Starting - ###");
for (var i = 0; i < objects.length; i++) {
// Iterate over numeric indexes from 0 to 5, as everyone expects.
}
console.log("### - Render: Complete - ###");
}
//Define generic move function
function transformR(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[37]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[38]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[39]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[40]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function transformL(object, moveAmount, canvasHeight, canvasWidth){
if (keyState[65]){
object[0] -= moveAmount
// console.log("left");
}
if (keyState[87]){
object[1] -= moveAmount
if (object[1] < 0){
// console.log("Top Edge")
object[1] = 0;
}
// console.log("up");
}
if (keyState[68]){
object[0] += moveAmount
// console.log("right");
}
if (keyState[83]){
object[1] += moveAmount
if (object[1] > (canvasHeight-object[3])){
// console.log("Bottom Edge")
object[1] = canvasHeight-object[3];
}
// console.log("down");
}
return object;
}
function collisonDetect(ball, paddle){
if (ball[0] < paddle[0] + paddle[2] &&
ball[0] + ball[2] > paddle[0] &&
ball[1] < paddle[1] + paddle[3] &&
ball[3] + ball[1] > paddle[1]) {
ball[8] = -ball[8];
ball[9] = -ball[9];
console.log("inside");
} else {
// console.log("not touching/inside");
}
return ball;
}
function ballMotion(height, width, ball, rightPaddle, leftPaddle){
var x = ball[0];
var y = ball[1];
// collision detection
ball = collisonDetect(ball, leftPaddle);
ball = collisonDetect(ball, rightPaddle);
var xSpeed = ball[8];
var ySpeed = ball[9];
x += xSpeed;
y += ySpeed;
// sides collison detection
if (y <= 0){
y = 0;
ySpeed = -ySpeed;
}
if (y >= height-ball[2]) {
y = height-ball[2];
ySpeed = -ySpeed;
}
if (x <= 0) {
x = 0;
xSpeed = -xSpeed;
leftPoints +=1
}
if (x >= width-ball[3]) {
x = width-ball[3];
xSpeed = -xSpeed;
rightPoints +=1
}
// assign new values
ball[0] = x;
ball[1] = y;
ball[8] = xSpeed;
ball[9] = ySpeed;
return ball;
}
function onPositionUpdate(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
console.log("Current position: " + lat + " " + lng);
}
function onDown(event){
cx = event.pageX;
cy = event.pageY;
console.log(cx, cy)
}
// Define objects as follows
// Renderer usage: Canvas context, x position, y position, object height, object width, red, green, blue, transparency
// Cut down usage: X, Y, height, width, red, green, blue, transparency
if (window.innerWidth < window.innerHeight) {
ballDim = [window.innerWidth*.02, window.innerWidth*.02]
} else {
ballDim = [window.innerHeight*.02, window.innerHeight*.02]
}
var ball = [window.innerWidth/2-((window.innerWidth*.02)/2), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), ballDim[0], ballDim[1],200 ,200 ,200 ,3 , 3, 2];
var leftPaddle = [window.innerWidth*.01, window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 0, 0, 200, 3];
var rightPaddle = [window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01), window.innerHeight*.8*.5-((window.innerHeight*.08)/2), window.innerWidth*.01, window.innerHeight*.08, 255, 100, 0, 3];
var leftPoints = 0;
var rightPoints = 0;
// Define gameLoop
function gameLoop(x,y) {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(onPositionUpdate);
} else {
console.log("navigator.geolocation is not available");
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown",onDown,false);
var width = window.innerWidth*.8;
var height = window.innerHeight*.8
ctx.canvas.width = width;
ctx.canvas.height = height;
var moveAmount = 3;
var motionTicker = + new Date()
// console.log(motionTicker)
// move checking function
leftPaddle[0] = window.innerWidth*.01;
rightPaddle[0] = window.innerWidth*.8-(window.innerWidth*.01)-(window.innerWidth*.01);
leftPaddle = transformL(leftPaddle, moveAmount, height, width);
rightPaddle = transformR(rightPaddle, moveAmount, height, width);
ball = ballMotion(height, width, ball, rightPaddle, leftPaddle);
ctx.save();
ctx.clearRect(0,0,width,height);
// Render objects in frame
drawObj(ctx, ball);
drawObj(ctx, leftPaddle);
drawObj(ctx, rightPaddle);
ctx.font = String(window.innerWidth*.05)+"px Arial";
ctx.fillStyle = "white";
ctx.fillText(String(rightPoints)+" - "+String(leftPoints), window.innerWidth*.333, window.innerHeight*.1);
ctx.restore();
setTimeout(gameLoop, 1);
await this.forceUpdate();
this.state = {motionTicker}
}
/components/CanvasCanvas.js
import * as React from "react";
export default class extends React.Component {
render() {
return (
<canvas ref={"canvas"} id = {"canvas"} width={640} height={425}/>
)
}
async componentDidMount() {
const script = document.createElement("script");
console.log("ln14")
script.src = "../src/gameLogic.js";
script.async = true;
// console.log(script);
document.head.appendChild(script);
console.log(script);
await this.setState(
{
text: this.props.text,
...this.state
}
);
await this.forceUpdate();
const canvas = this.refs.canvas;
const ctx = canvas.getContext("2d");
ctx.fillText((this.state && this.state.text) ? this.state.text : "Not initialised (nullcheck)", 210, 75);
}
}
Expected result is the gameLogic js file will render its output inside the canvas element and forceUpdate it at the end of each 'frame'.
And the actual result is a string of 404's as follows:
http://localhost:3000/css/style.css net::ERR_ABORTED 404 (Not Found)
index.js:1 Warning: Extra attributes from the server: deluminate_imagetype
GET http://localhost:3000/src/gameLogic.js net::ERR_ABORTED 404 (Not Found)
Thanks for any help you can give in advance.
If you want to access these files after compilation put them inside the static folder for example script.src = "/static/gameLogic.js"
Or use dynamic import
import dynamic from 'next/dynamic'
const gameLogic = dynamic(() => import(`../src/gameLogic.js`))
dynamic-import doc

a website background similar to canva

okay so i am a beginner in web coding
so the thing is i want my website to look like this in the background of my website whenever i move the mouse over the background the wallpaper must appear for example exactly like the one in this site but i just don't know how to do that if someone will help me out with a code or some sort please
the link to the example is here
should i do it with the mouse over or javascript and how
https://www.canva.com/
I tried like this, it works for me
var image = document.querySelector('img');
var imageCanvas = document.createElement('canvas');
var imageCanvasContext = imageCanvas.getContext('2d');
var lineCanvas = document.createElement('canvas');
var lineCanvasContext = lineCanvas.getContext('2d');
var pointLifetime = 1000;
var points = [];
if (image.complete) {
start();
} else {
image.onload = start;
}
/**
* Attaches event listeners and starts the effect.
*/
function start() {
document.addEventListener('mousemove', onMouseMove);
window.addEventListener('resize', resizeCanvases);
document.body.appendChild(imageCanvas);
resizeCanvases();
tick();
}
/**
* Records the user's cursor position.
*
* #param {!MouseEvent} event
*/
function onMouseMove(event) {
points.push({
time: Date.now(),
x: event.clientX,
y: event.clientY
});
}
/**
* Resizes both canvases to fill the window.
*/
function resizeCanvases() {
imageCanvas.width = lineCanvas.width = window.innerWidth;
imageCanvas.height = lineCanvas.height = window.innerHeight;
}
/**
* The main loop, called at ~60hz.
*/
function tick() {
// Remove old points
points = points.filter(function(point) {
var age = Date.now() - point.time;
return age < pointLifetime;
});
drawLineCanvas();
drawImageCanvas();
requestAnimationFrame(tick);
}
/**
* Draws a line using the recorded cursor positions.
*
* This line is used to mask the original image.
*/
function drawLineCanvas() {
var minimumLineWidth = 25;
var maximumLineWidth = 100;
var lineWidthRange = maximumLineWidth - minimumLineWidth;
var maximumSpeed = 50;
lineCanvasContext.clearRect(0, 0, lineCanvas.width, lineCanvas.height);
lineCanvasContext.lineCap = 'round';
lineCanvasContext.shadowBlur = 30;
lineCanvasContext.shadowColor = '#000';
for (var i = 1; i < points.length; i++) {
var point = points[i];
var previousPoint = points[i - 1];
// Change line width based on speed
var distance = getDistanceBetween(point, previousPoint);
var speed = Math.max(0, Math.min(maximumSpeed, distance));
var percentageLineWidth = (maximumSpeed - speed) / maximumSpeed;
lineCanvasContext.lineWidth = minimumLineWidth + percentageLineWidth * lineWidthRange;
// Fade points as they age
var age = Date.now() - point.time;
var opacity = (pointLifetime - age) / pointLifetime;
lineCanvasContext.strokeStyle = 'rgba(0, 0, 0, ' + opacity + ')';
lineCanvasContext.beginPath();
lineCanvasContext.moveTo(previousPoint.x, previousPoint.y);
lineCanvasContext.lineTo(point.x, point.y);
lineCanvasContext.stroke();
}
}
/**
* #param {{x: number, y: number}} a
* #param {{x: number, y: number}} b
* #return {number} The distance between points a and b
*/
function getDistanceBetween(a, b) {
return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
}
/**
* Draws the original image, masked by the line drawn in drawLineToCanvas.
*/
function drawImageCanvas() {
// Emulate background-size: cover
var width = imageCanvas.width;
var height = imageCanvas.width / image.naturalWidth * image.naturalHeight;
if (height < imageCanvas.height) {
width = imageCanvas.height / image.naturalHeight * image.naturalWidth;
height = imageCanvas.height;
}
imageCanvasContext.clearRect(0, 0, imageCanvas.width, imageCanvas.height);
imageCanvasContext.globalCompositeOperation = 'source-over';
imageCanvasContext.drawImage(image, 0, 0, width, height);
imageCanvasContext.globalCompositeOperation = 'destination-in';
imageCanvasContext.drawImage(lineCanvas, 0, 0);
}
html,
body {
font-size: 0;
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
body {
background: url(https://wallpaperbrowse.com/media/images/pexels-photo-248797.jpeg) 0 0 / cover;
}
img {
display: none;
}
<img src="https://wallpaperbrowse.com/media/images/sunflowers-mr.jpg"/>

How to preview .ai , .pdf format images before upload and convert into base64 in angularjs?

I use this directive on input type="file" filread="uploadme.src", Now the challenging part is to first convert .ai/.pdf file to .jpg/.png/.gif and resize them and save the base64 text in API. I need solution to convert them first them resize using base64 Uri function as shown in code below.
app.directive("fileread", [function() {
return {
scope: {
fileread: "=",
fileName: '='
},
link: function(scope, element, attributes) {
element.bind("change", function(changeEvent) {
var file, name, reader, size, type;
var reader = new FileReader();
reader.onload = function(loadEvent) {
scope.fileName = {};
scope.$apply(function() {
var img = new Image();
img.src = (loadEvent.target.result);
img.onload = function() {
var size = calculateAspectRatioFit(this.width, this.height, 100, 100);
scope.fileName.size = "_" + size.width + "X" + size.height;
//Get resized image
scope.fileread = imageToDataUri(this, size.width, size.height);
}
scope.fileName.src = (loadEvent.target.result);
if (angular.isString(name)) {
return scope.fileName.name = name;
}
});
}
file = changeEvent.target.files[0];
name = file.name;
type = file.type;
size = file.size;
reader.readAsDataURL(file);
});
}
}
}]);
//Resize the image (in the example 640 x 480px)
function imageToDataUri(img, width, height) {
// create an off-screen canvas
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// set its dimension to target size
canvas.width = width;
canvas.height = height;
// draw source image into the off-screen canvas:
ctx.drawImage(img, 0, 0, width, height);
// encode image to data-uri with base64 version of compressed image
return canvas.toDataURL();
}
function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
var ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {
width: srcWidth * ratio,
height: srcHeight * ratio
};
}

Angularjs directive refresh

I have created WordCloud from angularjs using wordCloud directive,
So whenever I change the input to the cloud after generating word cloud for the first time, I am unable form word cloud.
This issue is being, I am not able to refresh the directive.
Say my html and js is ,
var app = angular.module("myApp", ["tangcloud"]);
app.controller("myCtrl", function($scope) {
$scope.words = [
{id: 1, word: "oke", size: 1},
{id: 2, word: "blabla", size: 6},
{id: 3, word: "test", size: 7},
{id: 4, word: "schaap", size: 2},
{id: 5, word: "deployment", size: 10},
{id: 6, word: "woord3", size: 3},
{id: 7, word: "wogamalord4", size: 4}];
});
<tang-cloud words="words" on-click="test(word)"></tang-cloud>
Say my directive going to be
angular.module('tangcloud', [])
.directive('tangCloud', ['$interpolate', '$compile', '$timeout', function ($interpolate, $compile, $timeout) {
var directive = {
restrict: 'E',
scope: {
words: '=',
onClick: '&',
spin: '='
},
template: function (tElement, tAttrs) {
var isClickable = angular.isDefined(tAttrs.onClick);
var clickAttr = isClickable ? 'ng-click="onClick({word : entry.word, id : entry.id})"' : '';
return "<div class='tangcloud'>" +
"<span ng-repeat='entry in words'" + clickAttr + ">{{entry.word}}</span>" +
"</div>";
},
compile: function (elem) {
elem.children().children()
.addClass('tangcloud-item-' + $interpolate.startSymbol() + 'entry.size' + $interpolate.endSymbol())
.addClass('tangcloud-item-hidden');
return function (scope, elem) {
var div = elem.children().eq(0)[0];
scope.width = div.offsetWidth;
scope.height = div.offsetHeight;
var centerX = scope.width / 2;
var centerY = scope.height / 2;
var outOfBoundsCount = 0;
var takenSpots = [];
if (scope.words) {
scope.words = shuffleWords(scope.words);
determineWordPositions();
}
function shuffleWords(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
function determineWordPositions() {
$timeout(function () {
var trendSpans = elem.children().eq(0).children();
var length = trendSpans.length;
for (var i = 0; i < length; i++) {
setWordSpanPosition(trendSpans.eq(i));
}
});
}
function setWordSpanPosition(span) {
var height = parseInt(window.getComputedStyle(span[0]).lineHeight, 10);
var width = span[0].offsetWidth;
var spot = setupDefaultSpot(width, height);
var angleMultiplier = 0;
while (spotNotUsable(spot) && outOfBoundsCount < 50) {
spot = moveSpotOnSpiral(spot, angleMultiplier);
angleMultiplier += 1;
}
if (outOfBoundsCount < 50) {
takenSpots.push(spot);
addSpanPositionStyling(span, spot.startX, spot.startY);
}
outOfBoundsCount = 0;
}
function setupDefaultSpot(width, height) {
return {
width: width,
height: height,
startX: centerX - width / 2,
startY: centerY - height / 2,
endX: centerX + width / 2,
endY: centerY + height / 2
};
}
function moveSpotOnSpiral(spot, angleMultiplier) {
var angle = angleMultiplier * 0.1;
spot.startX = centerX + (1.5 * angle) * Math.cos(angle) - (spot.width / 2);
spot.startY = centerY + angle * Math.sin(angle) - (spot.height / 2);
spot.endX = spot.startX + spot.width;
spot.endY = spot.startY + spot.height;
return spot;
}
function spotNotUsable(spot) {
var borders = {
left: centerX - scope.width / 2,
right: centerX + scope.width / 2,
bottom: centerY - scope.height / 2,
top: centerY + scope.height / 2
};
for (var i = 0; i < takenSpots.length; i++) {
if (spotOutOfBounds(spot, borders) || collisionDetected(spot, takenSpots[i])) return true;
}
return false;
}
function spotOutOfBounds(spot, borders) {
if (spot.startX < borders.left ||
spot.endX > borders.right ||
spot.startY < borders.bottom ||
spot.endY > borders.top) {
outOfBoundsCount++;
return true;
} else {
return false;
}
}
function collisionDetected(spot, takenSpot) {
if (spot.startX > takenSpot.endX || spot.endX < takenSpot.startX) {
return false;
}
return !(spot.startY > takenSpot.endY || spot.endY < takenSpot.startY);
}
function addSpanPositionStyling(span, startX, startY) {
var style = "position: absolute; left:" + startX + "px; top: " + startY + "px;";
span.attr("style", style);
span.removeClass("tangcloud-item-hidden");
}
};
}
};
return directive;
}]);
How can I refresh my directive on change the input for my word-cloud

Resources