Got some trouble with canvas in html5 - html

I don't know where my code is broken.
Why my context is not recognized in my script?
I have trouble in this line :
this.context = this.canvas.getContext("2d");
Error message :
Uncaught TypeError: this.canvas.getContext is not a function
I'd like to know why my canvas doses not recognize?
Could you give me an advice?
var myGameArea = {
canvas : document.getElementById("canvas_screen"),
start : function() {
this.context = this.canvas.getContext("2d");
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
logger : function() {
alert("log---");
}
}

I tried your code in both Google chrome and Mozilla Firefox browser, but it seems to work fine.
Below is the code I tried:
<html>
<head>
<script type="text/javascript">
var myGameArea = {
canvas : document.getElementById("canvas_screen"),
start : function() {
this.context = this.canvas.getContext("2d");
this.interval = setInterval(updateGameArea, 20);
},
clear : function() {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
},
logger : function() {
alert("log---");
}
}
</script>
</head>
<body>
<canvas id="canvas_screen" style="z-index:0;background-color:#000000; position:fixed;top:20%;left:2%;">
</body>
</html>

Related

jquery function not working properly in safari

I am working on the following code. This function creates a "typed" effect. This function works well in chrome but not in safari. Is there an issue with jquery for safari?
var Typed = (function() {
var typed = '.typed',
$typed = $(typed);
function init($this) {
var el = '#' + $this.attr('id'),
strings = $this.data('type-this'),
strings = strings.split(',');
var options = {
strings: strings,
typeSpeed: 100,
backSpeed: 70,
loop: true
};
var animation = new Typed(el, options);
inView(el).on('enter', function() {
animation.start();
}).on('exit', function() {
animation.stop();
});
}
if ($typed.length) {
$typed.each(function() {
init($(this));
});
}
})();
<span class="typed" id="type-example-1" data-type-this="text1., text2., text3., text4."></span>

canvas is throw error of tainted after LoadFromJson

I am using fabric js version 1.7.22
when image set in a repetitive manner in a rectangle of fabric js, at
the first time it will be loaded and saved into JSON using toJSON()
and save an image using todataUrl() method, but when cal canvas a loadFromJson method at that time, this canvas not savable, because it throws tainted canvas error.
Please help me,
I already set crossOrigin in a pattern but it not working. and not
added in canvas JSON.
I have made one Fiddle For Generate Issue :
[http://jsfiddle.net/Mark_1998/kt387vLc/1/][1]
Steps to generate issue :
click on 'set pattern'
then click on 'save canvas'
then click on 'reload canvas' // load canvas from JSON
then click on 'save canvas' // cause issue of tainted canvas
This issue is fixed in new version of fabricjs already. If you are still using 1.7.20 the override fabric.Pattern.prototype.toObject and fabric.Pattern.prototype.initialize, find code in snippet.
var canvas = new fabric.Canvas('canvas', {
height: 500,
width: 500,
});
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
var canvasJSON = {};
document.getElementById('setPat').addEventListener('click', function() {
fabric.util.loadImage('https://cdn.dribbble.com/assets/icon-backtotop-1b04df73090f6b0f3192a3b71874ca3b3cc19dff16adc6cf365cd0c75897f6c0.png', function(image) {
var pattern = new fabric.Pattern({
source: image,
repeat: 'repeat',
crossOrigin: 'Anonymous'
});
var patternObject = new fabric.Rect({
left: 0,
top: 0,
height: canvas.height,
width: canvas.width,
angle: 0,
fill: pattern,
objectCaching: false
})
canvas.add(patternObject);
}, null, {
crossOrigin: 'Anonymous'
});
})
document.getElementById('saveCanvas').addEventListener('click', function() {
console.log('save canvas');
canvasJSON = canvas.toJSON();
var image = canvas.toDataURL("image/png", {
crossOrigin: 'Anonymous'
}); // don't remove this, i need it as thumbnail.
//console.log('canvas.Json', canvasJSON);
//console.log('image', image);
canvas.clear();
canvas.backgroundColor = '#ff0000';
canvas.renderAll();
});
document.getElementById('reloadCanvas').addEventListener('click', function() {
console.log('save canvas');
canvas.loadFromJSON(canvasJSON, function() {
canvas.set({
crossOrigin: 'Anonymous'
})
});
console.log('canvas.Json', canvasJSON);
});
//cross origin was not added in toObject JSON
fabric.Pattern.prototype.toObject = (function(toObject) {
return function() {
return fabric.util.object.extend(toObject.call(this), {
crossOrigin: this.crossOrigin,
patternTransform: this.patternTransform ? this.patternTransform.concat() : null
});
};
})(fabric.Pattern.prototype.toObject);
//cross origin was not added while creating image
fabric.Pattern.prototype.initialize = function(options, callback) {
options || (options = {});
this.id = fabric.Object.__uid++;
this.setOptions(options);
if (!options.source || (options.source && typeof options.source !== 'string')) {
callback && callback(this);
return;
}
// function string
if (typeof fabric.util.getFunctionBody(options.source) !== 'undefined') {
this.source = new Function(fabric.util.getFunctionBody(options.source));
callback && callback(this);
} else {
// img src string
var _this = this;
this.source = fabric.util.createImage();
fabric.util.loadImage(options.source, function(img) {
_this.source = img;
callback && callback(_this);
}, null, this.crossOrigin);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<button id="setPat">
Set pattern
</button>
<button id="saveCanvas">
Save canvas
</button>
<button id="reloadCanvas">
Reload CAnvas
</button>
<canvas id="canvas"></canvas>

Interstitial Ad doesn't appear

I can't do a simply html page with an Interstitial Add. I'm new in programming and I have no idea what's wrong in this code. I'm doing an app with phonegap. I added also <gap:plugin name="com.admob.plugin" version="3.0.0" source="plugins.cordova.io" /> to my config.xml. Please help. That's what I already have:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript">
function showInterstitial(){
admob.isInterstitialReady(function(isReady){
if(isReady){
admob.showInterstitial();
}else{
alert("need cached before show");
}
});
}
function onInterstitialReceive (message) {
alert("onMInterstitialReceive ,you can show it now");
}
function onReceiveFail (message) {
var msg=admob.Error[message.data];
if(msg==undefined){
msg=message.data;
}
alert("load fail: "+message.type+" "+msg);
}
function onDeviceReady() {
admob.initAdmob("ca-app-pub-5461976332457981/1789654352","ca-app-pub-5461976332457981/7220849555");
document.addEventListener(admob.Event.onInterstitialReceive, onInterstitialReceive, false);
document.addEventListener(admob.Event.onInterstitialFailedReceive,onReceiveFail, false);
}
document.addEventListener('deviceready',onDeviceReady, false);
</script>
</body>
</html>
Use the new plugin specification (with hyphens instead of dots):
<gap:plugin name="phonegap-admob" source="npm"/>
Then your code should be like this (you can also see here an example on how autoshow interstitials every 2 minutes: https://github.com/appfeel/admob-google-cordova/wiki/setOptions):
var isAppForeground = true;
var isInterstitialAvailable = false;
function onAdLoaded(e) {
if (isAppForeground && e.adType === admob.AD_TYPE.INTERSTITIAL) {
isInterstitialAvailable = true;
}
}
function onAdOpened(e) {
if (isAppForeground && e.adType === admob.AD_TYPE.INTERSTITIAL) {
isInterstitialAvailable = false;
admob.requestInterstitialAd(); // Request next interstitial
}
}
function onPause() {
if (isAppForeground) {
admob.destroyBannerView();
isAppForeground = false;
isInterstitialAvailable = false;
}
}
function onResume() {
if (!isAppForeground) {
setTimeout(admob.createBannerView, 1);
setTimeout(admob.requestInterstitialAd, 1);
isAppForeground = true;
}
}
function registerAdEvents() {
document.addEventListener(admob.events.onAdLoaded, onAdLoaded);
document.addEventListener(admob.events.onAdOpened, onAdOpened);
document.addEventListener("pause", onPause, false);
document.addEventListener("resume", onResume, false);
}
function initAds() {
var ids = {
ios : {
banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
},
android : {
banner : "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB",
interstitial : "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII"
}
};
var admobid = (/(android)/i.test(navigator.userAgent)) ? ids.android : ids.ios;
admob.setOptions({
publisherId: admobid.banner,
interstitialAdId: admobid.interstitial,
autoShowInterstitial: false,
isTesting: true // False on production apps
});
registerAdEvents();
}
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
if (window.admob) {
initAds();
admob.createBannerView(); // display a banner at startup
admob.requestInterstitialAd(); // cache an interstitial
} else {
alert('Admob plugin not ready');
}
}
document.addEventListener("deviceready", onDeviceReady, false);
function showInterstitial() {
if (isInterstitialAvailable) {
admob.showInterstitialAd();
} else {
console.log('Interstitial is not yet available');
}
}

jquery sidebar putting next to each other

I have put together a sidebar with hover-delay animation, but I can't seem to exactly copy the column to place next to the first. This is my first problem.
The second is that I would like to use the jspanel plugin, so that a dragable window will pop up when I click on a sub-item in the sidebar.
I hope this can be brought to a working state.
Thank you very much for responses in advance!
Here's [a link] (http://jsfiddle.net/chrisoutwright/tc4d9t6d/)!
$('#categories').corner("top keep");
$(document).ready(function(){
$("#foo").click(function(){
$().jsPanel().show();
});
});
$( "#navigation ul.sub-level" ).corner("").css( "border", "3px double blue" );
jQuery.fn.hoverWithDelay = function(inCallback,outCallback,delay) {
this.each(function() {
var timer, $this = this;
$(this).hover(function(){
timer = setTimeout(function(){
timer = null;
inCallback.call($this);
}, delay);
},function() {
if (timer) {
clearTimeout(timer);
timer = null;
} else
outCallback.call($this);
});
});
};
var hovering = {mainMenu: false, categories: false};
function closeSubMenus() {
$('ul.sub-level').css('display', 'none');
}
closeSubMenus();
function closeMenuIfOut() {
setTimeout(function(){
if (!hovering.mainMenu && !hovering.categories) {
$('#navigation').fadeOut('fast',closeSubMenus);
}
},100);
}
$('ul.top-level li').hoverWithDelay(function() {
$(this).find('ul').show();
}, function() {
$(this).find('ul').fadeOut('fast', closeMenuIfOut);
}, 500);
$('#categories').hoverWithDelay(function() {
$('#navigation').show();
hovering.categories = true;
},
function(){
hovering.categories = false;
closeMenuIfOut();
},500);
$('#navigation').hover(function() {
hovering.mainMenu = true;
}, function() {
hovering.mainMenu = false;
});
I can see at least one error in line 4 where you try to generate/open the jsPanel.
Which jsPanel version do you use? Version 1.x or Version 2.x? The two versions differ on how to use the jsPanel() command.
version 1.x: $( selector ).jsPanel( config );
version 2.x: $.jsPanel( config );
Do you get any error messages?

Converting an external init function into a polymer one

I want to create a polymer out of this codrops tutorial
http://tympanus.net/codrops/2013/07/03/interactive-particles-slideshow/
I can create a basic component but the script particlesSlideshow.js does not fire.
I think this is because I need to move its code into the polymer init script but im not sure how to do this.
Here is the script in the file. Any ideas how to move this across to polymer. I suppose I want to know what goes in the init and what can stay in an external file.
var self = window;
;(function(self) {
var canvas,
context,
particles = [],
text = [],
nextText = [],
shape = {},
mouse = { x: -99999, y: -99999 },
currentTransition = 'circle',
left, right,
layout = 0,
type = ['circle', 'ovals', 'drop', 'ribbon'],
FPS = 60,
/*
* List words.
*/
words = [ 'circle', 'ovals', 'drop', 'ribbon' ],
/*
* List colors.
*/
colors = {
circle: [ '#e67e22', '#2c3e50' ],
ovals: [ '#c0392b', '#ff7e15' ],
drop: [ '#1d75cf', '#3a5945' ],
ribbon: [ '#702744', '#f98d00' ]
};
/*
* Init.
*/
function init() {
console.log(document.querySelector('.ip-slideshow').length);
console.log(shadow.querySelector('.ip-slideshow').length);
var slideshowContainer = document.querySelector('.ip-slideshow');
canvas = document.createElement('canvas');
canvas.width = innerWidth;
canvas.height = 500;
slideshowContainer.appendChild(canvas);
// Browser supports canvas?
if(!!(capable)) {
context = canvas.getContext('2d');
// Events
if('ontouchmove' in window) {
canvas.addEventListener('touchup', onTouchUp, false);
canvas.addEventListener('touchmove', onTouchMove, false);
}
else {
canvas.addEventListener('mousemove', onMouseMove, false);
}
// Arrows
handleClick('bind', 'left');
handleClick('bind', 'right');
window.onresize = onResize;
createParticles();
// Arrows elements
left = document.querySelector('.ip-nav-left');
right = document.querySelector('.ip-nav-right');
// Show right arrow
right.classList.add('ip-nav-show');
}
else {
console.error('Sorry, switch to a better browser to see this experiment.');
}
}
/*
* Checks if browser supports canvas element.
*/
function capable() {
return canvas.getContext && canvas.getContext('2d');
}
/*
* On resize window event.
*/
function onResize() {
canvas.width = window.innerWidth;
canvas.height = 500;
// Reset the text particles, and align again on the center of screen
nextText = [];
updateText();
}
function scrollX() {
return window.pageXOffset || window.document.documentElement.scrollLeft;
}
......
/*
* Request new frame by Paul Irish.
* 60 FPS.
*/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / FPS);
};
})();
window.addEventListener ? window.addEventListener('load', init, false) : window.onload = init;
})(self);
If you change the script such that instead of
window.addEventListener ? window.addEventListener('load', init, false) : window.onload = init;
you did something like
self.initParticlesSlideshow = init;
Then you could invoke it in the domReady of an element like this:
Polymer('my-element', {
domReady: function() {
initParticlesSlideshow();
}
});
There are many other ways to do this, and a lot of other details; I'm just trying to get you started. =P